xusanduo08 / CSS

CSS学习笔记
0 stars 0 forks source link

getBoundingClientRect() #4

Open xusanduo08 opened 4 years ago

xusanduo08 commented 4 years ago

获取元素距离页面顶部的距离

element.getBoundingClientRect() + window.scrollY

或者

element.getBoundingClientRect() + document.documentElement.scrollTop
xusanduo08 commented 4 years ago

没有getBoundingClientRect()的话如何获取元素相对于文档顶部位置

var top = 0; // 距离文档顶部的距离
var left = 0; // 距离文档左边的距离
while(ele){
  top += el.offsetLeft;
  left += el.offsetTop;
  ele = ele.offsetParent;
}

var innerTop = top - window.scrollY; // 距离视口顶部的距离
var innerLeft = left - window.scrollX; // 距离视口左边的距离
xusanduo08 commented 4 years ago

getBoundClientRect() 返回一个DOMRect对象 getClientRects() 返回一个DOMRectList 类对象,包含元素内每个盒子的数据(块级元素返回的list只有一个元素,而行内元素可以返回多个,每行一个)

xusanduo08 commented 4 years ago

background-clip:控制元素背景图或者背景图片是否延伸到边框下面 background-clip: border-box 延伸到边框 background-clip: padding-box 延伸到内边距 background-clip: content-box 不延伸,仅覆盖内容区域

xusanduo08 commented 4 years ago

em不是相对于父元素的font-size,是相对于自己的font-size

xusanduo08 commented 4 years ago

window.scrollY:文档从顶部开始滚动过的像素值 为了跨浏览器兼容性,需要使用window.pageYOffset代替window.scrollY