使用jQuery怎么获取当前鼠标位置并输出

今天就跟大家聊聊有关使用jQuery怎么获取当前鼠标位置并输出,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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");
}

完整示例代码如下:

<!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>

看完上述内容,你们对使用jQuery怎么获取当前鼠标位置并输出有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。