如何动态更改DIV标签的CSS样式属性? [英] How to dynamically change CSS style attribute of DIV tag?
问题描述
我们有一个div标签:<div id='div1' style="background-color:red"></div>
We have a div tag: <div id='div1' style="background-color:red"></div>
我想知道如何更改此div标签的样式属性:-
I would like to know how can we change the style attribute of this div tag:-
-
我们可以清除样式值吗?
Can we clear the style value?
我们可以将值附加到现有的style属性吗?
Can we append value to the existing style attribute ?
我们可以为样式属性设置新值
Can we set new value to style attribute
谢谢.
推荐答案
var div = document.getElementById('div1');
// Clear Value
div.setAttribute('style','');
// OR
div.removeAttribute('style');
// Set Style / Append Style
div.style.backgroundColor = '#ff0000';
添加或更改样式时,请勿直接修改样式属性,除非您希望将其全部删除.
Don't modify the style attribute directly when adding or changing styles unless you want to remove them all.
JavaScript removeAttribute: https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute Javascript样式: https://developer.mozilla.org/zh- US/docs/Web/API/HTMLElement.style
JavaScript removeAttribute: https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute Javascript Style: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style
这篇关于如何动态更改DIV标签的CSS样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!