请问为什么这里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"));    
阅读 2.8k
2 个回答

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');

首先,setAttribute这个方法是设置标签的属性的。而div只有一个属性:align,所以你的cg.setAttribute("align", "center")才会生效。DIV介绍
然后,你要设置的color是标签的样式,只能通过设置css来实现效果,当然你直接设置一个color属性,标签是接收到了,但是不会去渲染,因为div没有color这个属性。
最后,要修改样式,请统一使用css样式来设置。比如:

var cg=document.getElementById("box");
cg.style.align = 'center';
cg.style.color = 'navy';
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题