问题为:Cannot read property 'backgroundColor' of undefined
代码如下
效果如下
你写的js不用下面的标签进行包装呀?
script type="text/javascript">
$("form input").css("border", "2px dotted blue");
$("form fieldset input").css("backgroundColor", "yellow");//JS标准
$("form fieldset input").css("background-color", "yellow");//不推荐在JS中用
$("form fieldset input").css("background-Color", "yellow");//好奇试了下,这种写法中C大写也能显示(浏览器竟然支持,换做其它字母大写就不行了)
</script>
http://blog.csdn.net/lvjin110/article/details/24323521
首先 你的background-color 属性在哪里设置的?
其次 如果你的background-color属性是在...这里设置的话,用this.style.backgroundColor 是获取不到的,因为这个方法获取的是行间样式
(以下涉及的数据都是我在chrome里面测试的)
老哥,你写的是window.onclick,那么你取的this也是指的window,不是body也不是你写的div1啊,反正我试了这样是绝逼取不到style的,this.style是undefind......
另外XX.style.backgroundColor,这样取到的color值是你在style中指定的值,如果你么有指定,那么取到的值是空的......
如果你是想获取某个标签的浏览器默认背景色,谷歌火狐这样的浏览器需要用getComputedStyle,IE需要使用currentStyle......
另外如果是上面getComputedStyle这个方法取到的颜色是rgba的,像下面这样
所以我就按照你上面大概的需求写了一下,实现如下
var bodyy = document.getElementById('div1');
var tyle
bodyy.onclick = function () {
if(getComputedStyle){ //code for chrome Firefox
var compStyle = document.defaultView.getComputedStyle(this, false);
tyle = compStyle['backgroundColor'];
} else{//code for ie
var comstyle=div.currentStyle;
tyle=comstyle['backgroundColor'];
}
console.log(tyle === 'rgba(0, 0, 0, 0)')
tyle === 'rgba(0, 0, 0, 0)' ? this.style.backgroundColor ='rgba(255, 192, 203, 1)' : this.style.backgroundColor = 'rgba(0, 0, 0, 0)'
}
还有我在chrome里面测试的时候发现如果你不在div里面写点什么,就算指定了height:100%,它的高度也是0~~
共勉