this.style.backgroundColor在IE7 / 8中不起作用 [英] this.style.backgroundColor don't work in IE7/8

查看:149
本文介绍了this.style.backgroundColor在IE7 / 8中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
        p{
            border:1px solid #CCC;
            margin:5px;
            padding:5px;
        }
    </style>
    <script type="text/javascript">
        window.onload = changeColor;
        function changeColor() {
            for(var i =0; i < document.getElementById("main").getElementsByTagName("p").length; i++) {
                var obj = document.getElementById("main").getElementsByTagName("p")[i];
                if (window.addEventListener) {
                    obj.addEventListener('mousemove', function () {
                        this.style.backgroundColor ="#EEE";
                    }, false);
                    obj.addEventListener('mouseout', function () {
                        this.style.backgroundColor ="#FFF";
                    }, false);
                } else if (window.attachEvent) {
                    //for ie
                    obj.attachEvent('onmousemove', function () {
                        this.style.backgroundColor ="#EEE";
                    });
                    obj.attachEvent('onmouseout', function () {
                        this.style.backgroundColor ="#FFF";
                    });
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <p>1</p>
        <div id="main">
            <p>2.1</p>
            <p>2.2</p>
            <p>2.3</p>
        </div>
    </div>
</body>
</html>

它在Chrome,FireFox和ie9中运行良好,但无法在IE7 / 8中运行

it work well in Chrome、FireFox and ie9,but can't work in IE7/8

错误信息是:无法设置backgroundColor的属性值:对象为null或未定义

the error message is:Unable to set the property value of the "backgroundColor": the object is null or undefined

什么是我的?

推荐答案

在IE中使用 attachEvent 时, 设置为窗口对象,而不是发生事件的对象。

When using attachEvent in IE, this is set to the window object, not to the object that the event happened on.

在IE中,全局变量 window.event.srcElement 将包含事件的目标对象。

In IE, the global variable window.event.srcElement will contain the target object for the event.

您可以编写类似这样的解决方法,使所有事件处理程序的工作方式相同:

You could code a work-around like this to make all the event handlers work the same:

function hookEvent(event, obj, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(event, fn, false);
    } else {
        obj.attachEvent("on" + event, function() {return(fn.call(obj, window.event));});
    }
}

这将使 this 设置为事件的源对象,事件处理程序的参数是事件对象。

This will make it so that this is set to the source object of the event and that the argument to the event handler is the event object.

这篇关于this.style.backgroundColor在IE7 / 8中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆