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

posted @ 2019-05-16 17:06  随风飞起-英  阅读(5464)  评论(0编辑  收藏  举报