当前位置: 首页 > Web前端 > vue.js

vue获取页面元素相对位置

时间:2023-03-31 22:16:43 vue.js

今天在开发源码中发现一处需要获取元素的相对位置高度。我发现getBoundingClientRect有问题。用于获取元素相对于窗口的位置集合。达到我想要的要求,看到阮老师写的一篇用Javascript获取页面元素位置的文章,解决了我的问题。当我滚动到元素的位置时,我想将元素固定在head//html结构

    首页推荐
  • 最新版本
exportdefault{data(){return{isFixed:false,}},mounted(){if(this.$refs.subnav.getBoundingClientRect){this.scrollTop(this.$refs.subnav.getBoundingClientRect())}},methods:{//这是一个封装的方法scrollTop(h){console.log(h);this.utils.scrollTop((res)=>{this.isFixed=res.scrollH>h?true:false;})}}}utils.js//该函数主要作用是返回滚动高度和文档占窗口高度的百分比utils.scrollTop=function(callback){//页面总高度vartotalH=document.body.scrollHeight||文档.documentElement.scrollHeight;//视觉高度varclientH=window.innerHeight||文档.documentElement.clientHeight;varresult={}window.addEventListener('scroll',function(e){//计算有效高度varvalidH=totalH-clientH//滚动条的高度varscrollH=document.body.scrollTop||document.documentElement.scrollTop//percentageresult.percentage=(scrollH/validH*100).toFixed(2)result.scrollH=scrollH;callback&&callback(result)})}可以看到元素距离顶部595px,正常显示显示,当我先滚动一段距离,然后再次刷新,滚动条的位置也会记录之前的位置,这个是top是195px,也是正常的,因为getBoundingClientRect是基于浏览器的窗口,我想要我想要的是刷新浏览器,无论浏览器滚动条在哪里。我绑定的dom元素是按照文档的左上角定位的。距父层顶部的距离。它不能被赋值。要设置对象到页面顶部的距离,请使用style.top属性获取元素到文档顶部的距离。返回值是一个DOMRect对象,它是元素的getClientRects()方法返回的一组矩形,即:是与该元素相关的一组CSS边框。DOMRct对象包含一组用于描述边框的只读属性:左、上、右和下,以像素为单位。除了width和height之外的属性都是相对于视口的左上角的。getBoundingClientRect返回值top:元素上边框到窗口顶部的距离bottom:元素下边框到窗口顶部的距离left:元素左边框到窗口顶部的距离leftsideofthewindowright:元素右边框与窗口左侧之间的距离。窗口的滚动相应变化,则元素到页面顶部的距离,加上滚动距离this.$refs.subnav.getBoundingClientRect().top+window.scrollY;或者this.$refs.subnav.getBoundingClientRect().top+document.documentElement.scrollTop;window.scrollY不兼容ie9,如果需要兼容请看Window.scrollY修改以上代码if(this.$refs.subnav.getBoundingClientRect){vartop1=this.$refs.subnav.getBoundingClientRect().top+window.scrollYvartop2=this.$refs.subnav.getBoundingClientRect().top+document.documentElement.scrollTop;console.log(top1)console.log(top2)this.scrollTop(top)}效果如下,无论滚动条在哪个位置,都是相对于文档的左上角。阮一峰functiongetElementTop(element){varactualTop=element.offsetTop;    varcurrent=element.offsetParent;while(current!==null){      actualTop+=current.offsetTop;      current=current.offsetParent;    }    returnactualTop;}实现原理offsetTop可以返回元素距离offsetParent的距离property返回元素距离顶部的距离(如果父元素有定位,则返回最近的定位元素,否则返回body元素。元素可能有多个定位元素,需要获取距离递归逐层添加,特别说明:需要将body的外边距设置为0,使元素到body顶部的距离等于到文档顶部的距离修改上面的代码+document.documentElement.scrollTop;//getElementTop在va之上rtop3=getElementTop(this.$refs.subnav)console.log(top1)console.log(top2)console.log(top3)this.scrollTop(top)}效果总结如下三种获取位置的方法文档顶部的元素dom.getBoundingClientRect().top+window.scrollY;或者dom.getBoundingClientRect().top+document.documentElement.scrollTop;或者函数getElementTop(element){ varactualTop=element.offsetTop; varcurrent=element.offsetParent; while(current!==null){    actualTop+=current.offsetTop;    current=current.offsetParent; } returnactualTop;}参考文章使用Javascript获取页面元素位置获取元素到页面顶部的距离关于我