js如何获取鼠标指针在元素中的坐标?

JavaScript012

js如何获取鼠标指针在元素中的坐标?,第1张

代码如下:

<!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]

js获取DIV的位置坐标的方法大概有两种:

第一种:编辑代码:var odiv=document.getElementById('divid')

alert(odiv.getBoundingClientRect().left)

alert(odiv.getBoundingClientRect().top)

第二种:编辑代码function CPos(x, y) {this.x = x this.y = y} /*** 得到对象的相对浏览器的坐标*/ function GetObjPos(ATarget {var target = ATargetvar pos = new CPos(target.offsetLeft, target.offsetTop)var target =target.offsetParentwhile (target  pos.x += target.offsetLeft  pos.y += target.offsetTop target = target.offsetParent }return pos }var obj =  document.getElementById('divid') alert(GetObjPos(obj)['x'])//x坐标alert(GetObjPos(obj)['y'])//y坐标

SPAN 和 DIV 的区别在于,DIV(division)是一个块级元素,可以包含段落、标题、表格,乃至诸如章节、摘要和备注等。而SPAN 是行内元素,SPAN 的前后是不会换行的,它没有结构的意义,纯粹是应用样式,当其他行内元素都不合适时,可以使用SPAN