温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-04-06 18:14:37 来源:亿速云 阅读:122 作者:Leah 栏目:web开发

今天就跟大家聊聊有关使用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怎么获取当前鼠标位置并输出有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI