您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

js获取样式的方法

2024/3/22 7:03:24发布23次查看
js获取样式* { 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>
1. js获取样式的方式1通过style只能获取行内样式,对于非行内样式,则不能获取
var box = document.getelementbyid('box'); console.log(box.style.width); // "" console.log(box.style.height); // ""
2. js获取样式的方式2window.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)
3. 兼容写法,并去掉单位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获取样式的方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product