offset 即偏移量,使用offset 系列相关属性可以动态地得到该元素的位置(偏移)、大小等
获得元素距离带有定位父元素的位置获得元素自身的大小(宽度高度)注意:返回时都不带数值offset系列:
offset系列属性作用element.offsetParent返回作为该元素带有定位的父级元素 如果父级都没有定位则返回bodyelement.offsetTop返回元素相对带有定位父元素上方的偏移element.offsetLeft返回元素相对带有定位父元素左边框的偏移element.offsetWidth返回自身包括padding、边框、内容区的宽度,不包括margin,返回值不带单位element.offsetHeight返回自身包括padding、边框、内容区的宽度,不包括margin,返回值不带单位 <body> <div class="father"> <div class="son"></div> </div> <script> var father = document.querySelector(".father"); var son = document.querySelector(".son"); //1.可以得到元素的偏移量 位置 返回的不带单位的数值 console.log(father.offsetTop); console.log(father.offsetLeft); //以带有定位的父级元素为准 如果父级都没有定位则以body为准 console.log(son.offsetLeft); //2.可以得到元素的大小 宽度 和高度 (包括padding、边框、内容区的宽度,不包括margin) console.log(father.offsetWidth); console.log(father.offsetHeight); //3. 返回作为该元素带有定位的父级元素 如果父级都没有定位则返回body console.log(son.offsetParent); console.log(son.parentNode); //都是返回父亲,但parentNode返回的是最近一级的父亲 亲爸爸,不管父亲是否有定位 </script> </body>offset系列与style 区别:
offeststyleoffest可以得到任意样式表中的样式值style只能得到行内样式表中的样式值offest获得的数值是没有单位的style.width得到的是带有单位的字符串offestWidth包含padding + border +widthstyle.width只有width,不包含包含padding +和borderoffestWidth等属性是只读属性,只能获取不能赋值style.width是可读写属性,可以获取也可以赋值获取元素大小位置用offset,给元素更改值用style
分析:
在盒子内移动 mousemove,先设置点击事件首先得到鼠标在页面中的坐标(e.pageX , e.pageY)其次得到盒子在页面中的距离(box.offsetLeft , box.offsetTop)用鼠标距离页面中的坐标减去盒子在页面中的距离 得到鼠标在盒子内的坐标 <div class="box">盒子</div> <script> var box = document.querySelector(".box"); box.addEventListener("mousemove", function (e) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; console.log("水平距离为" + x + " 垂直距离为" + y); }); </script>