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

标签 javascript google-chrome dom 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 */
});

当与静态值一起使用时,例如 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/

相关文章:

javascript - 使用一个 jQuery AJAX 表单(或响应)返回两个数据库结果

javascript - 替换不可靠字符串中的已知文本 (OCR)

javascript - 浏览器发送 'OPTIONS' 请求而不是 Angular 4 中的 GET/POST

html - Chrome 渲染错误

javascript - 是否可以修改 DOM 以进行 SQL 注入(inject)攻击或其他恶意攻击?

javascript - 如何在所需位置添加动态创建的节点(标签)?

html - 是否可以在不重置 DOM 的情况下移动 <video> 元素?

带有 OR 的 javascript 数组声明

javascript - 窗口是否可以关闭?

javascript - Mo.js 对象扩展语法的替代方案