JS获取鼠标坐标并且根据鼠标位置不同弹出不同内容
程序员文章站
2022-07-05 20:49:33
获取鼠标坐标,并且根据鼠标所在div弹出不同内容:
获取鼠标坐标,并且根据鼠标所在div弹出不同内容:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <head><title>鼠标的距离</title> <script type="text/javascript"> var mousex; var mousey; function show(event) { var infodiv = document.getelementbyid('infodiv'); mouseover(event); document.getelementbyid("a").innerhtml = mousex+" "+mousey ; infodiv.style.display = "block"; //infodiv.innerhtml = mousex+" "+mousey; infodiv.style.left = mousex + 10 + "px"; infodiv.style.top = mousey + 10 + "px"; } function hide() { var infodiv = document.getelementbyid('infodiv').style.display = "none";; } function mouseover(obj) { e = obj || window.event; // 此处记录鼠标停留在组建上的时候的位置, 可以自己通过加减常量来控制离鼠标的距离. mousex = e.layerx|| e.offsetx; mousey = e.layery|| e.offsety; if(e.target.id == "aaa") { infodiv.innerhtml = "aaa"; } else if(e.target.id == "bbb") { infodiv.innerhtml = "bbb"; } else if(e.target.id == "ccc") { infodiv.innerhtml = "ccc"; } else if(e.target.id == "ddd") { infodiv.innerhtml = "ddd"; }else{ infodiv.innerhtml = "eee"; } } </script> </head> <body> <div onmousemove="show(event);" onmouseout="hide();" style="margin:150px ; background:#ff0; height:300px; width:300px; position:relative; ">鼠标相对于触发事件元素的位置<strong id="a"></strong> <div id="aaa">aaa</div> <div id="bbb">bbb</div> <div id="ccc">ccc</div> <div id="ddd">ddd</div> <div id="infodiv" style="display: none; position: absolute; width: 100px; height: 100px; background-color: #f1f19b;"></div> </div> </body> </html>
以上所述是小编给大家介绍的js获取鼠标坐标并且根据鼠标位置不同弹出不同内容,希望对大家有所帮助