我们如何使用 JavaScript 来获取声明的 CSS 值的值(例如使用 Chrome 的检查器检查元素时显示的值?我在网络上尝试和搜索的所有内容似乎只想给出计算值。
对于我的具体用例,我想知道 CSS 过渡结束时的宽度是多少,该宽度是在样式表中设置的,而不是内联的。当我使用 JavaScript 检查宽度时,我得到了计算出的宽度,在脚本中检索时该宽度位于转换的开始处,因此0即使在 300 毫秒内它将是声明的宽度,如320px.
我想这就是你所追求的:
$('#widen').on('click', function(e){
$('.example').addClass('wider');
$('#prefetch').text('The div will be: ' + getWidth('wider'));
});
function getWidth(className){
for (var s = 0; s < document.styleSheets.length; s++){
var rules = document.styleSheets[s].rules || document.styleSheets[s].cssRules; console.log(rules);
for (var r = 0; r < rules.length; r++){
var rule = rules[r]; console.log(rule);
if (rule.selectorText == '.'+className){
console.log('match!');
return rule.style.width;
}
}
}
return undefined;
}Run Code Online (Sandbox Code Playgroud)
.example {
width: 100px;
background-color: #ccc;
border: 1px solid black;
}
.wider {
width: 320px;
-webkit-transition: width 5s;
-moz-transition: width 5s;
-o-transition: width 5s;
transition: width 5s;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="example">This is a simple container.</div>
<button id="widen" type="button">Widen</button>
<span id="prefetch"></span>Run Code Online (Sandbox Code Playgroud)
请记住,我相信这仍然是跨域预防的受害者(如果 CSS 托管在 CDN/其他域上,您将无法检索styleSheet,因此无法访问最终的宽度。