窗口顶部的Javascript事件进入和离开?

时间:2015-08-26 22:23:19

标签: javascript window onmouseover onmouseout

我正在寻找鼠标事件来检测鼠标何时进入窗口顶部,并离开窗口的顶部。我不是指网页的顶部,而是窗口的顶部。

我试图将事件附加到页面上没有预先存在的“元素”,但我认为以编程方式将不可见的,固定的html元素添加到页面顶部可能没问题。

我喜欢使用onmousemove的clientY方法,但是这会反复触发,我不想要 - 只想要进入和离开。不希望我的代码必须处理多次激活。

这适用于任何网页 - 我对页面上的HTML没有任何控制权(我以编程方式添加到页面的元素除外)。

只需要支持现代浏览器,最简单的方法,没有jquery。

这种方法效果很好!但是它可以防止它背后的点击元素,这是不行的。

(function (){        
var oBanana = document.createElement("div"); 
oBanana.style.position = "fixed"
oBanana.style.top = "0"
oBanana.style.left = "0"
oBanana.style.height= "100px"
oBanana.style.width = "100%"
oBanana.addEventListener("mouseover", function(event) {alert('in');});
oBanana.addEventListener("mouseout", function(event) {alert('out');});
document.body.appendChild(oBanana);
})();

接下来我尝试了这个,它在页面顶部插入一个小热区。我意识到,由于我的情况,我不想在hotzone上鼠标移出 - 而是我想要鼠标悬停在热区以下的所有内容上。这是我的第一次尝试,但失败了因为hotzone获取了body事件,而且body事件反复触发:

(function (){        
var oHotzone = document.createElement("div"); 
oHotzone.id = "fullscreen-hotzone"
oHotzone.style.position = "fixed"
oHotzone.style.top = "0"
oHotzone.style.left = "0"
oHotzone.style.height= "10px"
oHotzone.style.width = "100%"
oHotzone.addEventListener("mouseover", function(event) {alert('hotzone');});
document.body.appendChild(oHotzone);
document.body.style.marginTop = "10px"
document.body.addEventListener("mouseover", function(event) {alert('body');});
})();

感谢任何帮助! THX!

2 个答案:

答案 0 :(得分:0)

使用vanilla javascript,这是最简单的。

功能:

 // create a one-time event
function onetime(node, type, callback) {

    // create event
    node.addEventListener(type, function(e) {
        // remove event
        e.target.removeEventListener(e.type, arguments.callee);
        // call handler
        return callback(e);
    });
}

实现:

 // one-time event
onetime(document.getElementById("hiddenTopElement"), "mouseenter", handler);
onetime(document.getElementById("hiddenTopElement"), "mouseleave" , hanlder);

// handler function
function handler(e) {
    alert("You'll only see this once!");
}

答案 1 :(得分:0)

我的OP可能已经说得更好了,但我对这个解决方案很满意。固定div阻止了身体下方的悬停事件,因此在鼠标离开热区之前不会发生身体悬停事件。完美。

// create hotzone and add event
var oHotzone = document.createElement("div"); 
oHotzone.id = "fullscreen-hotzone"
oHotzone.style.position = "fixed"
oHotzone.style.top = "0"
oHotzone.style.left = "0"
oHotzone.style.height= "10px"
oHotzone.style.width = "100%"
oHotzone.addEventListener("mouseenter", function(event) {alert('hotzone');});
document.body.appendChild(oHotzone);

document.body.addEventListener("mouseenter", function(event) {alert('body');});