JavaScript如何判断页面某个元素 在css中的backgroundColor值 在线等~~

fpy_061625 2010-09-13 02:51:04
function changeBgColor(element) {

alert(element.style.backgroundColor.value);
if(element.style.backgroundColor == "#123456") {
element.style.backgroundColor = "#111111";
} else {
element.style.backgroundColor = "#222222";
}
}

aler()出的值为 undefined 请问大虾 我改如何用JavaScript判断这个element在css中的backgroundColor值呢?
谢谢~~
...全文
445 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
籽沫 2010-09-13
  • 打赏
  • 举报
回复
element.style.backgroundColor.value

这个写法是不对的,在backgroundColor这个元素中是没有value的,一般value都是属于表单之类元素

你这样去获取肯定会得到“undefined”无法找到的,而且你想通过style获取背景色,必须在标签中用style定义了这个标签的背景色才能获取否则,默认第一次是空的!

bhbhxy 2010-09-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bhbhxy 的回复:]

[/Quote]
不好意思刚才1楼说错了,不是有没有引用标准的问题
是backgroundColor后面不应该再加value了
例子是可以运行的
WebAdvocate 2010-09-13
  • 打赏
  • 举报
回复
直接 alert 这个:element.style.backgroundColor
zhwlxsch 2010-09-13
  • 打赏
  • 举报
回复
alert(element.style.backgroundColor.value);
if(element.style.backgroundColor == "#123456") 这两句都不一样。

在上一句中应该没有value。
yingying901029 2010-09-13
  • 打赏
  • 举报
回复
不要用这种办法去判断背景色,因为,如果你alert出来看看就知道了,有时候返回的是undefined,有时候是 rgb(255,255,255)并非十六进制格式!如果一定要这么判断,请先转换为hex格式,请参考mootools的 rgbToHex,还是那句话,不同的浏览器返回的颜色格式并不相同,这种判断解决不了跨浏览器问题。
bhbhxy 2010-09-13
  • 打赏
  • 举报
回复
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div id="a" style="height:100px; width:100px; background:#fff"></div>
</body>
</html>
<script type="text/javascript">
function changeBgColor(element) {

alert(element.style.backgroundColor);
if (element.style.backgroundColor == "#123456") {
element.style.backgroundColor = "#111111";
} else {
element.style.backgroundColor = "#222222";
}
}
window.onload = function () {
changeBgColor(document.getElementById("a"));
}
</script>

原因是没有加上w3c声明
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
在老版本的HTML中可能没有backgroundColor这个属性

61,112

社区成员

发帖
与我相关
我的任务
社区描述
层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。
社区管理员
  • HTML(CSS)社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧