我目前正在制作 google chrome 扩展程序并使用此 javascript 动态更改悬停元素的背景颜色:
var bindEvent = function(elem ,evt,cb) {
//see if the addEventListener function exists on the element
if ( elem.addEventListener ) {
elem.addEventListener(evt,cb,false);
//if addEventListener is not present, see if this is an IE browser
} else if ( elem.attachEvent ) {
//prefix the event type with "on"
elem.attachEvent('on' + evt, function(){
/* use call to simulate addEventListener
* This will make sure the callback gets the element for "this"
* and will ensure the function's first argument is the event object
*/
cb.call(event.srcElement,event);
});
}
};
bindEvent(document,'mouseover', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
bindEvent(document,'mouseout', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
当与静态值一起使用时,例如 target.style.background = #FFFFFF;
当光标悬停在一个元素上时 target.style.background = #00000;
当光标离开元素时,它可以完美运行。但是,当我尝试获取 target.style.background
甚至 target.style.backgroundColor
的值时,我总是得到 rgb(255,255,255)
,不管元素的背景颜色是什么。
我知道怎么把rgb转hexa,怎么反,但是如果拿不到背景的初始值,那也没用。
所以,我的问题是:为什么 var foo = target.style.backgroundColor;
总是返回 rgb(255, 255, 255)
以及我如何获得正确的值?
附加说明:该扩展稍后将移植到其他浏览器,因此如果可能的话,跨浏览器解决方案会很好。
最佳答案
根据我的经验,target.style
仅填充内联样式。要获得包括 css 定义的样式,只需使用 getComputedStyle
方法。例如
//instead of this
target.style.backgroundColor
//try this
getComputedStyle(target).backgroundColor
*注意使用getComputedStyle
方法返回一个只读
对象,仍然应该使用target.style
来设置背景颜色。
关于Javascript - 获取悬停元素的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892725/