javascript - 请问为什么这里setAtrribute无法达到效果?
高洛峰
高洛峰 2017-04-11 11:28:51
[JavaScript讨论组]

前一个cg.setAttribute("align", "center");可以达到居中的效果;
但是后面的cg.setAttribute("color", "navy");无法达到更改颜色的目的。
而最后浏览器也alert了color值是navy...
源代码:

what the fuck?

what the fuck?

what the fuck?

what the fuck?

what the fuck?

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"));
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
巴扎黑

setAttribute操作的是HTML标签的属性。。color是css属性,是在style属性里的。。你这样直接.setAttribute('color',xxx)出来就变成:

<p id="box" color=xxx></p> 

应该是:

    cg.setAttribute('style', 'color:#f55');

或者:

cg.style.color='#f55';

或者:

cg.style.cssText='color:#f55';

或者:

cg.style.setProperty('color', '#f55');
巴扎黑

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

var cg=document.getElementById("box");
cg.style.align = 'center';
cg.style.color = 'navy';
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号