javascript - 请问为什么这里setAtrribute无法达到效果?
本文介绍了javascript - 请问为什么这里setAtrribute无法达到效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
前一个cg.setAttribute("align", "center");
可以达到居中的效果;
但是后面的cg.setAttribute("color", "navy");
无法达到更改颜色的目的。
而最后浏览器也alert了color值是navy...
源代码:
<div id="box">
<p class="op">what the fuck?</p>
<p class="op">what the fuck?</p>
<p class="op">what the fuck?</p>
<p class="op">what the fuck?</p>
<p class="op">what the fuck?</p>
</div>
var cg=document.getElementById("box");
alert(cg.getAttribute("align"));
cg.setAttribute("align", "center");
alert(cg.getAttribute("align"));
cg.setAttribute("color", "navy");
alert(cg.getAttribute("color"));
解决方案
setAttribute操作的是HTML标签的属性。。color是css属性,是在style属性里的。。你这样直接.setAttribute('color',xxx)出来就变成:
<div id="box" color=xxx></div>
应该是:
cg.setAttribute('style', 'color:#f55');
或者:
cg.style.color='#f55';
或者:
cg.style.cssText='color:#f55';
或者:
cg.style.setProperty('color', '#f55');
这篇关于javascript - 请问为什么这里setAtrribute无法达到效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文