43.获取元素位置 发表于 2019-05-10 | 分类于 Javascript 1234567891011121314151617181920212223242526272829303132<style> *{ margin: 0; padding: 0; } .father{ width: 200px; height: 200px; margin-top: 100px; margin-left: 100px; background: blue; overflow: hidden; /*position: relative;*/ } .son{ width: 100px; height: 100px; margin-top: 100px; margin-left: 100px; background: red; }</style><div class="father"> <div class="son"></div></div> let oSDiv = document.querySelector(".son"); oSDiv.onclick = function () { console.log(oSDiv.offsetLeft); console.log(oSDiv.offsetTop); } 没有定位时,输出两个200 如果加上position: relative,输出100 offsetLeft和offsetTop作用获取元素到第一个定位祖先元素之间的偏移位如果没有祖先元素是定位的, 那么就是获取到body的偏移位 left,top是定位的素材可以设置的属性