0

如果在伪元素之前或之后设置了“内容”属性,我如何检查 javascript(使用 jQuery)?在 chrome 中,window.getComputedStyle(elem, '::before').getPropertyValue('content')当 'content' 设置为空字符串和未设置内容时,都返回一个空字符串。

我想到了一种解决方案:设置其他属性,例如宽度和高度,并检查计算的样式是否受到影响;但是,我希望尽量减少对 getComputedStyle 的调用次数。

谢谢

4

4 回答 4

1

只需添加一个if truthy子句来测试它是否具有一定的价值。

例如:

var before = window.getComputedStyle(elem, ':before').getPropertyValue('content');
if(before && before!=="none"){//<-- (IE / FF fix) check it doesn't equal 'none'
    //content: is defined but it could still be an empty string
    alert("Before="+before);
} else {
    //there is no :before content: defined at all
}

这是演示。尝试更改 css:before内容以对其进行测试。


getComputedStyle(elem, ':before').content
此外,您可以通过使用而不是进一步减少代码
window.getComputedStyle(elem, ':before').getPropertyValue('content')

于 2014-09-16T16:01:16.987 回答
0

Chrome 和 Opera 对 PseudoElements 的 getComputedStyle() 有一个错误:

当 style#elem::before设置为{display: none;}{content: none}或 content 只是not set时,都返回 #elem 的计算样式。

但在实际应用中是没有问题的:display: none没有内容的PseudoElement 不会显示,所以必须设置内容才能显示。

css内容中必须引用

div::before { content: "something"}   or { content: "" } // empty string.

当您现在检索 .getComputedStyle(...).content 时,您得到的不是空字符串,而是一个带有两个引号的字符串。这样你就可以区分你的两种情况。

在javascript中使用 content 值时要小心,它必须用双引号引起来。

正如在 CSS3 中指定的内容可以明确设置为“无”:

#elem::before { content: none } // without quotes!

在这种情况下 FF 和 IE 返回none, Chrome 和 Opera 真的什么都没有。

JSFidle 在这里测试所有案例。

于 2014-09-16T16:03:24.770 回答
0

我建议使用window.getMatchedCSSRules,然后查看规则:

function hasBeforeContentProperty(elt) {
    return [].some.call(
        window.getMatchedCSSRules(elt, '::before'),
        function(rule) {
            return /content/.test(rule.cssText);
        }
    );
}

This needs some bullet-proofing and sanity testing, but the concept is find the rules applicable to the ::before pseudo-element, then examine their cssText property to see if a content is specified, whether as empty string or otherwise. Note that you need to do the textual scan of rule.cssText instead of looking at rule.style.content, since the latter will always be the empty string even if rule does not specify content.

于 2014-09-16T16:20:29.093 回答
-1

您需要使用真实的 DOM 元素而不是伪元素。不能通过 JavaScript 修改伪元素,不是 DOM 元素

于 2014-09-16T14:56:29.193 回答