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

31 篇文章 0 订阅
8 篇文章 0 订阅

  直接在.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");

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值