我可以通过JavaScript(getComputedStyle)在{content:'...'}字符串之前阅读:但这个字符串表现得很奇怪 [英] I can read a :before {content:'...'} string via JavaScript (getComputedStyle), but this string behaves weirdly
问题描述
我有以下设置。我创建一个< div>
,通过伪选择器附加术语之前:在
之前读取使用 getComputedStyle
的值。
I have the follwing setup. I create a <div>
, attach the term "before" through the pseudo-selector :before
and read that value by using getComputedStyle
.
这是有效的,我得到了成功的术语(在我的情况下是之前),它是string类型。 (请参阅控制台输出。)
This works, I get the term (which in my case is "before") successfully, it is of type "string". (See the console output.)
该字符串与给定字符串的比较将返回预期的 true
,但仅在Safari中, CodePen 和此处,在运行代码段 - 环境!
The comparison of that string with a given string returns the expected true
, but only in Safari, CodePen and here, in the "Run code snippet"-Environment!
它不适用于Chrome,Firefox或IE。匹配的比较返回 false
。
It does NOT work in Chrome, Firefox, or IE. The comparison of the match there returns false
.
这可能是什么原因?
为什么这个简单的字符串比较不起作用?
Why does this simple string-comparison not work?
三个相关的代码片段如下所示:
The three relevant snippets of code look like this:
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
。有些浏览器在字符串中返回字面引号,其他浏览器则不返回。
I found that different browsers treat getPropertyValue
for content
differently. Some browsers return literal quotes in the string, others don't.
Here is the fiddle that I used to test the behaviour across different browsers. The results below:
| 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
加价:
<div class="pseudo">Div with pseudo :before content.</div>
CSS:
div.pseudo:before {
content:'before';
color: red;
}
JS:
var content = window.getComputedStyle(document.querySelector('.pseudo'), '::before').getPropertyValue('content');
console.log(content == "before");
console.log(content == '"before"');
这篇关于我可以通过JavaScript(getComputedStyle)在{content:'...'}字符串之前阅读:但这个字符串表现得很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!