美文网首页
页面(屏幕)/元素的宽高/位置

页面(屏幕)/元素的宽高/位置

作者: 李霖弢 | 来源:发表于2019-08-22 14:33 被阅读0次

window属性

  • window.innerWidth/innerHeight
    浏览器窗口可视区大小 受viewport分辨率影响
    一般情况用该属性即可,但当横竖屏切换时,ios部分机型会出现其值不变,此时可使用document.body.clientWidth/clientHeight代替(注意此时body应设置{width:100vw,height:100vh},否则高度为0)
  • window.screen.width/height
    真实分辨率(物理屏幕分辨率)大小,包括微信头部等 例如IPhone6即为375
  • window.screen.availWidth/availHeight
    显示器的出厂硬件分辨率 不可变 通常和window.screen.width/height相同
  • window.screenTop/screenLeft
    浏览器窗口相对屏幕距离

元素属性

对于body直接用document.body.XXX即可,如使用document.body.offsetHeight获取整个文档的高度(不包含body的margin)

属性
  • offsetWidth/offsetHeight
    元素宽高,包括padding和border,不包括margin
  • clientWidth/clientHeight
    元素宽高,包括padding,不包括border和margin
  • offsetTop/offsetLeft
    获取当前元素到 定位父节点(最近且position属性为非static的祖先元素) 的top/left方向的距离(数字,不包含px),同jq的.position()中的内容
  • scrollWidth/scrollHeight
    元素内容真实的宽高,内容未溢出时同clientWidth
  • scrollTop/scrollLeft
    已滚动距离
方法
  • $(element).offset().top/left 相对HTML偏差
  • scrollIntoView() 让元素滚动到可视区
  • getBoundingClientRect() 获取元素相对视口的距离
    • bottom: 元素底边(包括border)到可视区最顶部的距离
    • left: 元素最左边(不包括border)到可视区最左边的距离
    • right: 元素最右边(包括border)到可视区最左边的距离
    • top: 元素顶边(不包括border)到可视区最顶部的距离
    • height: 元素的offsetHeight
    • width: 元素的offsetWidth
    • x: 元素左上角的x坐标 (ie不支持)
    • y: 元素左上角的y坐标 (ie不支持)

viewport

通过meta指定viewport宽640

<meta name="viewport" id="viewport" content="width=640,user-scalable=0>

或直接让viewport等同于物理分辨率

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

此时以下值相等

  • window.innerWidth
  • window.screen.width
  • window.screen.availWidth
  • 无border和margin的document.body.clientWidth
  • 无margin的document.body.offsetWidth
  • document.documentElement.clientWidth
  • document.documentElement.offsetWidth

判断当前可见区域某点处的顶层元素

x、y为该点从屏幕左上方开始的横纵坐标数值(单位为px)
如该点不在屏幕内则返回null

var element = document.elementFromPoint(x, y);

判断某点是否在视口内

var io = new IntersectionObserver(entries => {
  console.log(entries);//可见性发生变化的元素成员数组
}(, option));
// 开始观察
io.observe(document.getElementById('example'));
// 停止观察
io.unobserve(element);
// 关闭观察器
io.disconnect();
  • callback 可见性发生变化时(刚进入视口 或 完全离开视口)的回调函数,其参数为可见性发生变化的元素成员数组,成员具有
    • target(元素)
    • rootBounds(根元素的矩形区域的信息)
    • boundingClientRect(目标元素的矩形区域的信息)
    • intersectionRect(目标元素与视口或根元素的交叉区域的信息)
    • intersectionRatio(目标元素的可见比例,即intersectionRect占boundingClientRect的比例,0~1)
  • option
    • threshold 触发回调的门槛数组
    • root 指定祖先元素,默认为视口
    • rootMargin 所有的偏移量均可用像素(pixel)(px)或百分比(percentage)(%)来表达, 默认值为"0px 0px 0px 0px"。
{
  threshold: [0, 0.25, 0.5, 0.75, 1],
  root: document.querySelector('.container'),
  rootMargin: "500px 0px" 
}

相关文章

网友评论

      本文标题:页面(屏幕)/元素的宽高/位置

      本文链接:https://www.haomeiwen.com/subject/asunsctx.html