js如何获取鼠标在某元素移动时~鼠标指针在元素中的坐标?
发布网友
发布时间:2022-04-24 07:29
我来回答
共4个回答
热心网友
时间:2022-04-20 13:24
稍等上代码!!
<html>
<head>
<script type="text/javascript">
function show_coords(event){
var x = event.clientX;
var y = event.clientY;
var say = document.all("coords");
say.innerHTML = "X:"+x+" Y:"+y;
say.style.position = "absolute";
say.style.left = x + 30;
say.style.top = y;
}
</script>
</head>
<body onmousemove="show_coords(event)">
<p id="coords"></p>
</body>
<html>
希望我的回答对你有用,有用就采纳!!!谢谢!
热心网友
时间:2022-04-20 14:42
代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>获取鼠标在Canvas中的坐标位置</title>
<style>
#canvas{
border:1px solid #ccc;
width:300px;
height:300px;
overflow:hidden;
}
</style>
<script>
function get_canvas(ev,obj){
m_clientX = ev.clientX-obj.offsetLeft;
m_clientY = ev.clientY-obj.offsetTop;
document.getElementById("tips").innerHTML = "当前坐标:X:"+ m_clientX + " ,Y:" +m_clientY;
}
</script>
</head>
<body>
<div id="tips"></div>
<div id="canvas" onmousemove="get_canvas(event,this)"></div>
</body>
</html>
兼容IE8+
用 javascript 获取当前页面上鼠标(光标)位置在许多情况下都会用到,比如拖放,悬停提示(tooltip) 等等。当然,这里我们依然要面对浏览器的兼容问题,在不同的浏览器下,对这些相关的属性处理方式也不同。
参考资料
首页 → 网络编程 → JavaScript → javascript技巧 → js获取鼠标位置实例详解.脚本之家[引用时间2018-1-18]
热心网友
时间:2022-04-20 16:17
我们有代码:
<!DOCTYPE html>
<html>
<head>
<script>
function coordinates(event) {
document.getElementById("demo").innerHTML = "X = " + event.clientX + " Y = " +
event.clientX;
}
</script>
<style>
.div{width: 600px; height: 300px; border: blue 1px solid;}
.info{border: tomato 2px solid;}
</style>
</head>
<body>
<div onmousemove="coordinates(event)" class="div"></div>
<p>单击上面的图片可显示鼠标指针相对于屏幕的 x 和 y 坐标。</p>
<div id="demo" class="info"></div>
</body>
</html>
热心网友
时间:2022-04-20 18:08
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
*{margin: 0;padding: 0;list-style: none;}
.main{height: 500px;width: 500px;background: #cecece;margin: 20px auto;}
</style>
<body>
<div class='main'></div>
</body>
<script>
var main=document.getElementsByTagName('div')[0];
function init(){
main.addEventListener('mousemove',move,false)
}
init();
function move(e){
//var e=event || window.event;
var x=e.clientX-main.offsetLeft;
var y=e.clientY-main.offsetTop;
console.log(x+','+y)
}
</script>
</html>