js獲取當前鼠標位置並輸出


js獲取當前鼠標位置並輸出

1.html

<body onmousemove="mousemove(event)"></body>
2.css

html,
body {
width: 100%;
height: 100%;
background: #A5CEDB;
position: relative;
}

.newDiv {
position: absolute;
background: red;
color: white;
width: 100px;
height: 50px;
}
3.js

var movex;
var movey; //用來接受鼠標位置的全局變量
function mousemove(e) {
e = e || window.event;
if(e.pageX || e.pageY) {
movex = e.pageX;
movey = e.pageY
}
creatDiv(movex, movey);
}

function creatDiv(x, y) {
$(".newDiv").remove();
var str = ("<div class=\'newDiv\'>" + x + "," + y + "</div>");
$("body").append(str);
$(".newDiv").css("left", x + "px").css("top", y + "px");
}
效果:

 

(提示:可以在creatDiv方法里面酌情加入想要的偏移量)

原文:https://blog.csdn.net/weixin_40687883/article/details/81667657


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM