[英]Setting style property on a div element
我有以下div元素
<div style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
有没有办法使用JavaScript更改此div标签的style属性?
具体来说我想做以下事情:
将此样式属性设置为另一个字符串,例如style = "test"
创建一个新的样式属性,并用new属性替换该属性
即:
var new_style_a = document.createAttribute("style");
(somehow insert this new attribute into the div tag)
你需要首先获得一个对你的div的JS引用 - 为了简单起见,我们现在就给它一个ID;
<div id='myDiv' style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
然后在JS ......
document.getElementById('myDiv').style.color = '#FF0000';
编辑:反映您编辑的问题。 如果你只想将属性的值设置为某个字符串(对于记录,如果你这样做是影响风格的最佳方法),你可以这样做;
document.getElementById('myDiv').setAttribute('style','somestring');
再次编辑; 如果你坚持使用document.createAttribute
...
var attr = document.createAttribute('style');
attr.value = 'somestring';
document.getElementById('myDiv').setAttributeNode(attr);
有没有办法使用JavaScript更改此div标签的style属性? 具体来说我想要执行以下操作:将此样式属性设置为另一个字符串,例如style =“test”
如果要替换元素上的现有样式属性(或者如果不存在则创建一个),则使用:
document.getElementById('elemId').setAttribute('style','width:100px;');
如果要将新样式属性添加到现有规则,那么它将如下所示:
document.getElementById('elemId').style.setAttribute('width', '150px');
你需要能够引用那个div
。 最好是给它一个唯一的id
并使用getElementById
来引用它。
你需要让JS通过id引用你的div元素。
HTML
<div id="elem-change" style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
JS
if (document.getElementById("elem-change")) {
document.getElementById("elem-change").style.color = "#0000FF";
}
要么
document.getElementById('elem-change').setAttribute('style','color :#0000FF');
JQUERY
$("#elem-change").css("color", "#0000FF");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.