js如何获取某个html元素的x y坐标

JavaScript014

js如何获取某个html元素的x y坐标,第1张

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script src="js/jquery-3.2.1.min.js"></script>

</head>

<body>

<ul>

    <li>1234</li>

    <li>12345</li>

    <li>123456</li>

    <li>1234567</li>

</ul>

<script>

    $('ul').on('click','li',function (e) {

         console.log(e.clientX)

         console.log(e.clientY)

    })

</script>

</body>

</html>

1、新建一个html文件,命名为test.html。

2、在test.html文件内,创建一个div模块,并设置其id属性为mydiv,用于下面使用js获得标签对象。

3、在test.html文件内,在div标签内,填写一段文字,并加入一个span标签。

4、在test.html文件内,创建一个button按钮,按钮名称为“获取html”。

5、给button绑定onclick点击事件,当按钮被点击时,执行myfun()函数。

6、在test.html文件内,在js标签内,创建myfun()函数,在函数内,使用getElementById()方法获得div对象,通过innerHMTL属性获得div内的html内容,最后,使用alert方法将获得的html内容以弹窗形式显示

7、在浏览器打开test.html文件,点击按钮,查看获得的html标签内容。

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