我们在使用原生操作css样式的时候难免会一行一行的去操作,如
_dom.style.width = "100px";
_dom.style.height = "100px";
我这里提供了一种方式,其实我们可以通过给HTMLElement添加自定义的方法,让你让你像 $(Jquery).css() 一样的去操作css。 如:
_dom.css({width: '100px', height: '100px'});
下面是我的实现例子
<div id="test"></div>
<script type="text/javascript">
let _test = document.getElementById("test");
//以前添加样式
_test.style.width = "150px";
_test.style.height = "100px";
_test.style.backgroundColor = "antiquewhite";
_test.innerText = '2秒后修改样式'
setTimeout(()=>{
//给HTMLElement 添加一个 css函数用于设置样式
HTMLElement.prototype.css = function(style){
for(let k in style)
this.style[k.replace(/-[\w]/g, letter=>letter.replace('-','').toUpperCase())] = style[k];//把使用 - 隔开的名称改成驼峰式命名
}
//添加了 css 拓展方式后添加样式
_test.css({'background-color': 'red', borderBottom: '5px solid green'});//测试
}, 2000);
</script>
网友评论