在悬停事件中恢复dom对象

时间:2014-06-18 09:06:50

标签: javascript

我正在尝试创建hover事件。为了实现这一点,我需要在执行函数之前保持初始元素状态。

obj.prototype.onhover = function(callback){
    window.hoverElement = this.element; //store element in global variable before changing its state.
    this.element.onmouseover = function(){
        callback(this);
    };
    this.element.onmouseout = function(){
        console.log(window.hoverElement,this); //why these 2 elements are the same?
        this.parentNode.replaceChild(window.hoverElement,this); //restore initial state
        delete window.hoverElement;
    };
};

但是,console.log输出完全相同的元素。

我的代码出了什么问题?为什么window.hoverElement存储已经更改的元素?我怎么能解决它?

1 个答案:

答案 0 :(得分:0)

我希望您通过阅读以下评论来理解它:

obj.prototype.onhover = function(callback){
    window.hoverElement = this.element; // 'window' is a global variable. 'this' refers to the obj scope.
    this.element.onmouseover = function(){
        callback(this);
    }.bind(this);
    this.element.onmouseout = function(){
        console.log(window.hoverElement,this); // 'this' is referring to hovered element scope. So, window.hoverElement === this
        this.parentNode.replaceChild(window.hoverElement,this); //restore initial state
        delete window.hoverElement;
    }.bind(this);
};