Skip to content

图示元素的DOM位置

dom 尺寸和位置

尺寸1

![尺寸2](https://zongyan30.github.io/front-assets/03-JS收官/20220406223123.png null)

![尺寸3](https://zongyan30.github.io/front-assets/03-JS收官/20220213212313.png null)

尺寸4

调用dom.scrollTo(x, y)可以设置元素的滚动位置,x 和 y 分别表示 scrollLeft 和 scrollTop

该方法通用元素回到元素顶部dom.scrollTo(0, 0)

如果要监听元素的滚动,可以监听事件类型:==scroll==

Element.getBoundingClientRect()

![element-box-diagram](https://zongyan30.github.io/front-assets/03-JS收官/202210151248555.png null)

上图中的 top、left、right、bottom 均相对于视口

汇总

  1. window 的尺寸
innnerWidth innerHeight浏览器内部尺寸(含滚动条)
clientWidth clientHeight视口内容区尺寸(不含滚动条)
outerWidth outerHeigtht浏览器外部尺寸
screen.width screen.height屏幕宽高
scrollX scrollY文档滚动偏移
pageXOffset pageYOffset页面滚动的距离

window.scrollX、window.pageXOffset: 相当于根元素的scrollLeft window.scrollY、window.pageYOffset: 相当于根元素的scrollTop

方法:

  • scrollTo()、scrollBy()
  • resizeTo()、resizeBy()  //只能设置通过js代码打开的窗口,对于用户自己打开的窗口无效。
  1. 元素的尺寸位置尺寸
offsetWidth offsetHeight盒子实际尺寸占位( 包含内容 + 内边距 + 边框 + 滚动条)
clientWidth clientHeight盒子在可见内容区的尺寸 (包含内容 + 内边距,不含边框和滚动条宽度)
scrollWidth scrollHeight元素内容的总尺寸(包括被滚动条实际撑大的区域,不含边框)
scrollTop scrollLeft元素内部滚动与内容尺寸(内部内容滚动的距离)

位置

offsetParent获取某个元素第一个定位的祖先元素 如果没有则得到body
offsetTop offsetLeft相对于 offsetParent 的偏移量(受定位上下文影响)
getBoundingClientRect()获取元素的矩阵信息 视口坐标系(相对于视口) 包含内边距与边框,不含外边距

body的offsetParent为null,如果offsetParent是body,则将其当作是整个网页

  1. 鼠标事件参数
clientX clientYMouseEvent 鼠标位置(相对视口的坐标)
pageX pageYMouseEvent 相对于文档的坐标 (包含滚动偏移)
offsetX、offsetY鼠标相对于事件源的内边距边缘的坐标
screenX screenYMouseEvent 相对于整个屏幕的坐标
x、y等同于clientX、clientY
movementX、movementY只在鼠标移动事件中有效,相对于上一次鼠标位置,偏移的距离

movementX、movementY会随着笔记本缩放随着变化,100%下表现正常

  1. js 常用 API

scrollIntoView

将元素滚动到可是区域,不可设置具体的像素值

javascript
dom.scrollIntoView({
  block: "top",
  behavior: "smooth",
});

scrollTo/scrollBy

文档滚动控制,可指定具体坐标      scrollTo是指将滚动条设置到指定位置   scrollBy()是指在原来的位置上再增加/减少指定值

js
window.scrollTo({
  top: 50,
  behavior: "smooth",
});

ResizeObserver()

观测元素内容盒尺寸变化,替代轮询

js
const ro = new ResizeObserver((entries) => {
  for (const e of entries)
    console.log(e.contentRect.width, e.contentRect.height);
});

ro.observe(document.querySelector(".box"));

IntersectionObserver

是否与视口相交,常用于判断元素是否进入视口,懒加载常用

javascript
const io = new IntersectionObserver(
  ([e]) => {
    if (e.isIntersecting) {
      console.log("相交了");
    }
  },
  { threshold: 0.5 },
); //阈值:50%可见才触发

io.observe(document.querySelector(".box"));

MIT License