js的offsetleft屬性的用法小結(jié)
obj.offsetleft, 此屬性是只讀的,不能夠賦值
此屬性可以返回當前元素距離某個父輩元素左邊緣的距離:
- 如果父輩元素中有定位的元素,那么就返回距離當前元素最近的定位元素邊緣的距離。
- 如果父輩元素中沒有定位元素,那么就返回相對于body左邊緣距離。
實例一:有定位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>demo1</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#main{
width:300px;
height:300px;
background:red;
position:absolute;
left:100px;
top:100px;
}
#box{
width:200px;
height:200px;
background:blue;
margin:50px;
overflow:hidden;
}
#inner{
width:50px;
height:50px;
background:green;
text-align:center;
line-height:50px;
margin:50px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var inner=document.getElementById("inner");
document.getElementById("msg").innerHTML = 'offsetLeft='+inner.offsetLeft;
}
</script>
</head>
<body>
<div id="msg"></div>
<div id="main">main(position:absolute)
<div id="box">box
<div id="inner"></div>
</div>
</div>
</body>
</html>結(jié)果

返回inner元素距離main元素的左側(cè)的距離,因為main元素是第一個定位父輩元素。
實例二(無定位)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>demo2</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#main{
width:300px;
height:300px;
background:red;
margin:100px;
}
#box{
width:200px;
height:200px;
background:blue;
overflow:hidden;
}
#inner{
width:50px;
height:50px;
background:green;
text-align:center;
line-height:50px;
margin:50px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var inner=document.getElementById("inner");
document.getElementById("msg").innerHTML = 'offsetLeft='+inner.offsetLeft;
}
</script>
</head>
<body>
<div id="msg"></div>
<div id="main">
main
<div id="box">
box
<div id="inner">inner</div>
</div>
</div>
</body>
</html>結(jié)果:

返回inner元素距離body元素左側(cè)的尺寸。
到此這篇關(guān)于js的offsetleft屬性的用法小結(jié)的文章就介紹到這了,更多相關(guān)js offsetleft屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何使用webpack5+TypeScript+npm發(fā)布組件庫
這篇文章主要介紹了如何使用webpack5+TypeScript+npm發(fā)布組件庫,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-04-04
JavaScript+html5 canvas實現(xiàn)圖片破碎重組動畫特效
這篇文章主要介紹了JavaScript+html5 canvas實現(xiàn)破碎重組的視頻特效,感興趣的小伙伴們可以參考一下2016-02-02
JavaScript代碼壓縮工具UglifyJS和Google Closure Compiler的基本用法
網(wǎng)上搜索了,目前主流的Js代碼壓縮工具主要有Uglify、YUI Compressor、Google Closure Compiler,簡單試用了UglifyJS 和Google Closure Compiler 兩種工具的基本用法,需要的朋友可以參考下2020-04-04
微信小程序?qū)崿F(xiàn)跟隨菜單效果和循環(huán)嵌套加載數(shù)據(jù)
這篇文章主要為大家詳細介紹了微信小程序?qū)崿F(xiàn)跟隨菜單效果和循環(huán)嵌套加載數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11

