我正在制作一个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转换为16进制并进行反转,但如果我无法获取背景的初始值,那就没用了。
因此,我的问题是:为什么
var foo = target.style.backgroundColor;
总是返回rgb(255, 255, 255)
,我该如何获取正确的值?附加说明:该扩展程序稍后将被移植到其他浏览器中,因此最好提供跨浏览器的解决方案(如果可能的话)。
getComputedStyle(target).backgroundColor
替换了target.style.backgroundColor
,现在根据悬停的背景颜色,我得到了不同的结果!谢谢。 @marksyzm:我会记住这个方法,在做IE扩展时使用。 - Caramel Truffle