Javascript-获取悬停元素的背景颜色

Car*_*fle 3 javascript dom google-chrome google-chrome-extension

我目前正在制作一个 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 */
});
Run Code Online (Sandbox Code Playgroud)

当与静态值一起使用时,例如target.style.background = #FFFFFF;当光标悬停在元素上以及target.style.background = #00000;当光标离开元素时,它可以完美地工作。但是,当我尝试获取target.style.background或 的值时target.style.backgroundColorrgb(255,255,255)无论元素的背景颜色是什么,我总是会得到 。

我知道如何将rgb转换为hexa以及如何反转它,但是如果我无法获取背景的初始值,那就没有用了。

所以,我的问题是:为什么var foo = target.style.backgroundColor;总是返回rgb(255, 255, 255)以及如何获得正确的值?

附加说明:该扩展稍后将移植到其他浏览器,因此如果可能的话,跨浏览器解决方案会很好。

Bea*_*ist 5

根据我的经验,target.style仅填充内联样式。要获取包含 css 定义的样式,只需使用该getComputedStyle方法。例如

//instead of this
target.style.backgroundColor

//try this
getComputedStyle(target).backgroundColor
Run Code Online (Sandbox Code Playgroud)

*请注意,使用该getComputedStyle方法返回一个read-only对象,并且target.style仍然应该用于设置背景颜色。

  • @marksyzm 然而,IE9+ 支持它。无论如何,我认为已经没有多少人再为 IE6 开发了。他还想获取悬停时元素的颜色,而不是元素的悬停颜色。 (2认同)