JS 设置 DIV 的位置

JavaScript07

JS 设置 DIV 的位置,第1张

var p = document.getElementById("div1")

p.style.position = "absolute"

p.style.left="100px"

p.style.top="100px"

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

先获取到div元素

用offsetTop和offsetLeft获取div相对顶部和左边的距离

代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Document</title>

</head>

<body>

<div id="div1">第一个div</div>

<script>

  var div1 = document.getElementById("div1")

  alert("距顶:"+div1.offsetTop+",距左:"+div1.offsetLeft)

</script>

</body>

</html>