* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 100px;
margin: 100px;
padding: 50px;
border: 20px solid #33ff11;
background-color: #ff4343;
}<p id="box" class="box"></p>
通过style只能获取行内样式,对于非行内样式,则不能获取
var box = document.getElementById('box');
console.log(box.style.width); // ""
console.log(box.style.height); // ""window.getComputedStyle IE9以下不兼容 使用currentStyle
console.log(window.getComputedStyle(box, null)); // 返回的是对象CSSStyleDeclaration console.log(window.getComputedStyle(box, null).width); // 200px console.log(window.getComputedStyle(box, null).margin); // 100px console.log(window.getComputedStyle(box, null).backgroundColor); // rgb(255, 67, 67)
function getStyle(ele, attr) {
var val = null, reg = null;
if (window.getComputedStyle) {
val = window.getComputedStyle(ele, null)[attr];
} else {
val = ele.currentStyle[attr];
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i; // 正则匹配单位
return reg.test(val) ? parseFloat(val) : val;
}
console.log(getStyle(box, 'width')); // 200
console.log(getStyle(box, 'border')); // 20px solid rgb(51, 255, 17)以上就是js获取样式的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号