Posted in jQuery onJanuary 05, 2019
本文实例讲述了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>3water.com 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代码运行工具:
http://tools.3water.com/code/HtmlJsRun
在线HTML/CSS/JavaScript前端代码调试运行工具:
http://tools.3water.com/code/WebCodeRun
希望本文所述对大家jQuery程序设计有所帮助。
jQuery实现获取当前鼠标位置并输出功能示例
- Author -
The_road_of_ordinary声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@