微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – onmousemove事件不会从外部源中触发?

我在我的网页上的div中加载了一个外部网页(在本例中为www.duckduckgo.com).我希望在div内外得到我的鼠标X和Y位置,但是当我在div内部时,似乎网页阻止了onmousemove事件的触发.但是,onmouSEOver事件在进入div时仅触发一次.

以下示例代码说明了我的问题:

function mouseEvent(event) {
      var x = event.clientX;
      var y = event.clientY;

      document.getElementById('label').innerHTML = 'X=' + x + ' Y=' + y;
}
html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;        
    overflow: hidden;
    margin-left: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    margin-right: 0px;
}
#form1 {
    height: 100%;
    width: 100%;
}
#pageDiv {
    height: 100%;
    width: 100%;
}
#page {
    height: 100%;
    width: 100%; 
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="pageDiv"> 
            <label id="label">hello</label>
            <object id="page" type="text/html" data="https://duckduckgo.com/" onmousemove="mouseEvent(event)" onmouSEOver="mouseEvent(event)">
            </object>
        </div>
    </form>
</body>
</html>

如何在此网页上的任何位置获取鼠标X和Y位置(即不只是在持有外部源的div顶部)?我尝试添加event.preventDefault();到mouseEvent函数的开头,但在帮助领域没有做任何事情.

我猜测外部网页正在偷走我的注意力.是这样的吗?无论如何我可以实现常数X和Y坐标更新?

解决方法

function mouseEvent(event) {
      var x = event.clientX;
      var y = event.clientY;

      document.getElementById('label').innerHTML = 'X=' + x + ' Y=' + y;
}

function removeCheat() {
     // remove cheat div or remove right/bottom position. 
     // Not sure what your ultimate goal is.
}
html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;        
    overflow: hidden;
    margin-left: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    margin-right: 0px;
}
#form1 {
    height: 100%;
    width: 100%;
}
#pageDiv {
    height: 100%;
    width: 100%;
}
#page {
    height: 100%;
    width: 100%; 
}
#cheat {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div id="cheat" onmousemove="mouseEvent(event)" onmouSEOver="mouseEvent(event)" onmousedown="removeCheat()"></div>
    <form id="form1" runat="server">
        <div id="pageDiv"> 
            <label id="label">hello</label>
            <object id="page" type="text/html" data="https://duckduckgo.com/">
            </object>
        </div>
    </form>
</body>
</html>

原文地址:https://www.jb51.cc/js/156702.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐