本文實例講述了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.49028c.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.VeVB.COm/code/HtmlJsRun
在線HTML/CSS/JavaScript前端代碼調試運行工具:
http://tools.VeVB.COm/code/WebCodeRun
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery拖拽特效與技巧總結》、《jQuery常用插件及用法總結》、《jquery中Ajax用法總結》、《jQuery表格(table)操作技巧匯總》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答