我可以通过JavaScript(getComputedStyle)在{content:’…’}字符串之前阅读:但这个字符串表现得很奇怪

前端之家收集整理的这篇文章主要介绍了我可以通过JavaScript(getComputedStyle)在{content:’…’}字符串之前阅读:但这个字符串表现得很奇怪前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下设置.我创建一个< div>,通过伪选择器附加术语“之前”:之前使用getComputedStyle读取该值.

这是有效的,我得到的术语(在我的情况下是“之前”)成功,它是“字符串”类型. (参见控制台输出.)@H_502_3@

该字符串与给定字符串的比较将返回预期的true,但仅限于Safari,CodePen和此处的“运行代码段” – 环境!@H_502_3@

它不适用于Chrome,Firefox或IE.匹配的比较返回false.@H_502_3@

可能是什么原因呢?@H_502_3@

为什么这个简单的字符串比较不起作用?@H_502_3@

代码的三个相关代码段如下所示:@H_502_3@

var content = window.getComputedStyle(document.querySelector('.pseudo'),'::before').getPropertyValue('content');
console.log('content: ' + content); // "before"
console.log('typeof content: ' + typeof content); // string
console.log(content == "before"); // false
document.write(content == "before"); // false
div.pseudo:before {
  content: "before";
  color: red;
}
<div class="pseudo">
  Div with pseudo :before content.
</div>

解决方法

我发现不同的浏览器对内容的getPropertyValue处理方式不同.有些浏览器会返回字符串中的字面引号,而其他浏览器则不会.

这是我用来测试不同浏览器行为的fiddle.结果如下:@H_502_3@

                                 | before | "before"
---------------------------------+--------+---------
Chrome 42.0.2311.135             | true   | false 
Chrome Canary 44.0.2394.0        | false  | true 
Firefox 37.0.2                   | false  | true
Firefox Developer Edition 39.0a2 | false  | true
Internet Explorer 11.09          | false  | true
Safari 8.0.5                     | true   | false
Opera 29.0.1795.47               | true   | false

标记:@H_502_3@

<div class="pseudo">Div with pseudo :before content.</div>

CSS:@H_502_3@

div.pseudo:before {
    content:'before';
    color: red;
}

JS:@H_502_3@

var content = window.getComputedStyle(document.querySelector('.pseudo'),'::before').getPropertyValue('content');

console.log(content == "before");
console.log(content == '"before"');
原文链接:https://www.f2er.com/js/153972.html

猜你在找的JavaScript相关文章