offset大家族(一)
文章目录
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>offset大家族</title>
<style type="text/css"> body,html{ margin:0; padding:0;
} .grandpa{ margin-left:50px; width:500px; height:300px; background:#ff9933; position:relative; border:5px solid #33ff00;
} .father{ width:300px; height:300px; background:#ff3366; padding:20px; border:5px solid #ffff00;
} .son{ width:100px; height:100px; background:#0000ff; padding:10px; border:5px solid #ccffcc;
}
</style>
</head>
<body>
<div class="grandpa">
<div class="father" style="position:absolute;left:300px">
<div class="son" style="left:300px" ></div>
</div>
</div>
<script type="text/javascript">
var father=document.querySelector(".father"); var grandpa=document.querySelector(".grandpa"); var son=document.querySelector(".son"); console.log(son.offsetWidth);//130
console.log(son.offsetHeight);//130
console.log(son.offsetLeft);//25
console.log(son.offsetTop);//25
console.log(son.offsetParent.className);//grandpa
console.log(son.parentNode);//<div class="father"></div>
console.log(son.style.left);//300px 这里虽然获得300px 但是由于没有设置position属性所以不起作用
console.log(father.style.left);//300px
son.offsetLeft="300"; console.log(son.offsetLeft);//20
son.style.left="500px"; console.log(son.style.left); /* offsetWidth 元素本身的宽度 content+padding+border 动态 offsetHeight 元素本身的高度 content+padding+border 动态 offsetLeft 此元素左外边框到有定位的长辈的边框距离 就近长辈 offsetTop 此元素右外边框到有定位的长辈的边框距离 就近长辈 js没有right 和 bottom 所以 right=son.offsetLeft+son.offsetWidth top=son.offsetTop+son.offsetHeight 1. son.style.left 访问的话只能得到行内的style值 这样的div class="son" style="position:absolute;top:300px"></div> 2. 行内样式如果没有设置top值 style.top 得到的是空字符串 "" 3.offsetLeft 得到的是数字 30 而style.left得到的是字符串 30px 4.offsetLeft 是 onlyRead 就是只可以get 不能set style.left 可以set 也可以get 5.offsetLeft 可以返回没有设置定位属性盒子的left 而style.left 不行 没有设置定位属性的盒子没有left top属性 虽然可以获得行内设置的left style.left 300px <div class="box" style="left:300px"></div> 但是没有作用 因为没有设置position 5. 如果想访问css style 还可以用以下方法 标准浏览器window.getComputedStyle(son)["left"]; IE son.currentStyle("left"); offsetParent 得到最近的有定位的长辈 比较记忆 parentNode 得到父节点 */
</script>
</body>
</html>
转载于猿2048:➜《offset大家族(一)》

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论