当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现获取当前鼠标位置并输出功能示例

jQuery实现获取当前鼠标位置并输出功能示例

2019年06月01日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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>

效果:

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

ps:感兴趣的朋友可以使用如下工具测试上述代码的运行效果:

在线html/css/javascript代码运行工具:

在线html/css/javascript前端代码调试运行工具:

更多关于jquery相关内容感兴趣的读者可查看本站专题:《jquery拖拽特效与技巧总结》、《jquery常用插件及用法总结》、《jquery中ajax用法总结》、《jquery表格(table)操作技巧汇总》、《jquery扩展技巧总结》、《jquery常见经典特效汇总》、《jquery动画与特效用法总结》及《jquery选择器用法总结

希望本文所述对大家jquery程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网