js如何获取鼠标在某元素移动时~鼠标指针在元素中的坐标? 65
当鼠标在这个图片元素中移动时,我如何用js或者jquery获得鼠标相对这个元素左上角的X和Y坐标值? 展开
稍等上代码!!
<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>
希望我的回答对你有用,有用就采纳!!!谢谢!
那个~你直接用clientX和clientY,这里得到的是鼠标相对整个页面的坐标吧~我想知道如何才能得到相对于鼠标某元素的坐标~
额。。那需要再获取一下该元素相对于页面的坐标,然后把两个值相减就可以了!!
<html>
<head>
<style>
</style>
<script type="text/javascript">
var left,top;
window.onload= function () {
var image = document.getElementById('img');
top1 = parseInt(image.style.top);
console.log(top1)
left = image.style.left;
console.log(left)
}
function show_coords(event){
var x = event.clientX-parseInt(left);
var y = event.clientY-parseInt(top1);
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 >
<img id="img" src="/6rooms/html/img/1.jpg" alt="" onmousemove="show_coords(event)" style="position: absolute;
top:50px; left: 200px;">
<p id="coords"></p>
</body>
<html>
看一下代码!!!
代码如下:
<!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]
<!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>
<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>