常见的使用 JS 来动态操作 css方法,你应该了解这些

编程入门 行业动态 更新时间:2024-10-27 19:23:55

  直接在.style对象上设置样式属性将需要使用驼峰式命名作为属性键,而不使用短横线命名;如果需要设置更多的内联样式属性,则可以通过设置.style.cssText属性,以更加高效的方式进行设置 。

const el = document.createElement('div')el.style.backgroundColor = 'red'
// 或者 
el.style.cssText = 'background-color: red'
// 或者
el.setAttribute('style', 'background-color: red')

  cssText 的本质就是设置 HTML 元素的 style 属性值, but 给cssText设置后原先的css样式被清掉了

<div id="d1">煮一壶生死悲欢祭少年郎</div>
<script>document.getElementById("d1").style.cssText = "color:red; font-size:13px;";console.log(document.getElementById("d1").style.cssText);// color: red; font-size: 13px;
</script>

如果这种设置内联样式过于繁琐,还可以考虑将.styleObject.assign()一起使用,以一次设置多个样式属性。

const el = document.createElement('div');Object.assign(el.style, {backgroundColor: "red",margin: "25px"
})

使用obj.className来修改样式表的类名

el.className = "class-one class-two";el.setAttribute("class", "class-one class-two");

更多精彩 请移步:by.wlgzs.club:8082/articles/2019/12/04/1575461558363.html

更多推荐

你应该,常见,操作,方法,动态

本文发布于:2023-05-20 22:56:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/156766.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:你应该   常见   操作   方法   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!