我正在尝试创建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
存储已经更改的元素?我怎么能解决它?
答案 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);
};