也許這樣,這個選擇頁面上的每個元素,然後檢查它是computed style爲font-weight設定爲'bold'(也可以是由'b「或」strong)。如果它符合此規則,那麼該元素將記錄到控制檯。
注意:getComputedStyle檢測到'b'和'strong',因此不需要額外的測試來檢測這些元素。
CSS
.boldText {
font-weight : bold;
}
HTML
<div>Some text</div>
<div class='inBold'>Hello <b>Dude</b>
</div>
<div class='inBold'>Hello <span class="boldText">Dude</span>
</div>
<div class='inBold'>Hello <strong>Dude</strong>
</div>
的Javascript
Array.prototype.forEach.call(document.querySelectorAll("*"), function (element) {
if (window.getComputedStyle(element).fontWeight === "bold") { // can also use .getPropertyValue("font-weight")
console.log("bold: ", element);
}
});
在jsfiddle
當然這是檢查網頁上的所有,但它是發非常簡單地尋找你需要的文本,並使用這個原則檢查那些元素。
通過改變這一行:
if (element.textContent === "Dude" && window.getComputedStyle(element).fontWeight.toLowerCase() === "bold") {
在jsfiddle
注:不支持舊版瀏覽器上的getComputedStyle,二者也並非支持所有Array.forEach
document.querySelectorAll舊版瀏覽器。
Array.forEach有很多墊片,或者可以將其更改爲for或while循環。
getComputedStyle更像是一個問題,但如果你需要更多的跨瀏覽器的東西,那麼這應該給你更廣泛的支持。
的Javascript
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function textContent(node) {
if (typeof node.textContent !== "undefined" && node.textContent !== null) {
return node.textContent;
}
var text = ""
walkTheDOM(node, function (current) {
if (current.nodeType === 3) {
text += current.nodeValue;
}
});
return text;
}
function camelCase(string) {
return string.replace(/-([a-z])/g, function (matched) {
return matched[1].toUpperCase()
});
}
function getComputedStyleProperty(element, property) {
if (!window.getComputedStyle) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(element).getPropertyValue(property);
} else {
var camelCased = camelCase(property);
if (element.currentStyle) {
return element.currentStyle[camelCased];
} else {
return element.style[camelCased];
}
}
} else {
return window.getComputedStyle(element).getPropertyValue(property);
}
}
var elements = document.getElementsByTagName("*"),
length = elements.length,
i = 0,
element;
while (i < length) {
element = elements[i];
if (textContent(element) === "Dude" && getComputedStyleProperty(element, "font-weight") === "bold") {
console.log("bold: ", element);
}
i += 1;
}
在jsfiddle
http://stackoverflow.com/about – Xotic750 2013-05-11 09:26:03
@ Xotic750該鏈接在哪裏適用於當前上下文? – Exception 2013-05-14 04:38:18
「堆棧溢出是一個問題和答案網站」,在兩週內沒有任何活動,您是否找到解決方案?如果沒有以下建議,那麼也許你可以分享你的答案,甚至將它標記爲你選擇的問題的答案。 「這個網站都是關於獲取答案的」,引用來自上面的鏈接。 – Xotic750 2013-05-14 12:47:35