1.
offset一定要注意父亲要有定位,返回的偏移值是没有单位的。
<script>
// offset 系列
var father = document.querySelector('.father');
var son = document.querySelector('.son');
// 1.可以得到元素的偏移 位置 返回的不带单位的数值
console.log(father.offsetTop);
console.log(father.offsetLeft);
// 它以带有定位的父亲为准 如果么有父亲或者父亲没有定位 则以 body 为准
console.log(son.offsetLeft);
var w = document.querySelector('.w');
// 2.可以得到元素的大小 宽度和高度 是包含padding + border + width
console.log(w.offsetWidth);
console.log(w.offsetHeight);
// 3. 返回带有定位的父亲 否则返回的是body
console.log(son.offsetParent); // 返回带有定位的父亲,一直往上找 若没有,返回的是body
console.log(son.parentNode); // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位
</script>
2.offset和style的区别(获取用offset,改值用style)
3.鼠标在盒子里的坐标
<div class="box"></div>
<script>
// 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
// 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
// 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
// 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标
var box = document.querySelector('.box');
box.addEventListener('mousemove', function(e) {
// console.log(e.pageX);
// console.log(e.pageY);
// console.log(box.offsetLeft);
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
})
</script>
4.模态框案例
框子跟着鼠标走的重点是,先获取鼠标点击时相对于框子的位置,这个是固定的
然后鼠标移动,这个相对位置不变,鼠标坐标-相对位置就是框子的新位置
鼠标移动和弹起的事件要写在按下事件的内部。
cursor样式可以改变鼠标的光标