美文网首页
JS设置元素多属性

JS设置元素多属性

作者: 前端历险记 | 来源:发表于2016-04-04 18:18 被阅读896次

jquery为element设置多属性很简单,见下:

$('#bigbox').css({
'background':'#666',
'width':'400px',
'height':'100px'
})

js默认的方式,逐条添加,遇到需要添加多次属性的情况,费事,好处是兼容没问题,见下:

var bigBox = document.getElementById('bigbox');
bigBox.style.backgroundColor = 'red';
bigBox.style.width = '400px';
bigBox.style.height = '100px';

想要修改多重属性,也可以使用setAttribute,存在的缺陷是:会覆盖掉默认的或已经修改过的属性,见下:

var bigBox = document.getElementById('bigbox');
bigBox.setAttribute('style' , 'width:400px; height:300px; background-color:blue')

更为推荐的方法是使用cssText,见下:

var bigBox = document.getElementById('bigbox');
bigBox.style.fontSize = '20px';
bigBox.style.cssText += 'color:#fff; background-color: #f96e5b; height: 100px;';

参考:
MDN-Style
MDN-cssText
ChangeSingle or Multiple Css Properties

相关文章

网友评论

      本文标题:JS设置元素多属性

      本文链接:https://www.haomeiwen.com/subject/mdzulttx.html