2019-01-07 11:01:39 431浏览
今天扣丁学堂HTML5培训老师给大家结合实例讲述了jQuery实现获取当前鼠标位置并输出功能,下面我们一起来看一下吧。jQuery获取当前鼠标位置并输出
<body onmousemove="mousemove(event)"></body>
html,
body {
width: 100%;
height: 100%;
background: #A5CEDB;
position: relative;
}
.newDiv {
position: absolute;
background: red;
color: white;
width: 100px;
height: 50px;
}
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");
}
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.jb51.net js获取当前鼠标位置</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
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");
}
</script>
<style>
html,
body {
width: 100%;
height: 100%;
background: #A5CEDB;
position: relative;
}
.newDiv {
position: absolute;
background: red;
color: white;
width: 100px;
height: 50px;
}
</style>
</head>
<body onmousemove="mousemove(event)"></body>
</html>
【关注微信公众号获取更多学习资料】