VUE锚点定位
// 点击此处<div @click="goDingyue">立即订阅</div>
绑定事件
methods: {goDingyue() {// 获取元素在页面中的位置console.log(this.$refs.dingyue_box_ref.getBoundingClientRect());// document// .getElementById("agentTitle")// .scrollIntoView({ block: "start", behavior: "smooth" });// 跳转到指定位置并且平滑滚动this.$el.querySelector(".dingyue_box").scrollIntoView({ block: "start", behavior: "smooth" });},
}
<div class="dingyue_box" ref="dingyue_box_ref">立即订阅内容</div>
然后获取页面位置等等
理解:getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性。
2.返回值类型:
rectObject.top:元素上边到视窗上边的距离;
rectObject.right:元素右边到视窗左边的距离;
rectObject.bottom:元素下边到视窗上边的距离;
rectObject.left:元素左边到视窗左边的距离;
scrollIntoView是一个与页面(容器)滚动相关的API(官方解释),该API只有boolean类型的参数能得到良好的支持(firefox 36+都支持),所以在这里只讨论参数Boolean类型的情况。
调用方法为 element.scrollIntoView() 参数默认为true。
参数为true时调用该函数,页面(或容器)发生滚动,使element的顶部与视图(容器)顶部对齐;
参数为false时,使element的底部与视图(容器)底部对齐。
TIPS:页面(容器)可滚动时才有用!
document.getElementById("view").scrollIntoView();
二 锚点定位的介绍:
锚点其实就是可以让页面定位到某个位置上的点。在高度较高的页面中经常见到。
// 锚点跳转有两种形式:// *1. a标签 + name / href 属性// *2. 使用标签的id属性//2.1 第一种锚点定位的方法:<a href="#box1">我跳到box1</a><a href="#" name="#box2">我跳到box2</a><div id="box1"></div><div id="box2"></div>
// 2.2 第二种锚点定位的方法://JQuery的写法<script>$('a').on('click',function(e){//阻止a标签的默认行为跳转,这样就不会把#判断符带入到url中e = e || window.event;e.preventDefault();// 获取id号,得到是#box1var target = $(this).prop('hash');//将页面滚动到对应的位置$('html,body').scrollTop($(target).offset().top);});
</script>//原生写法:
<script>var aList = document.querySelectorAll('a');//给每一个a标签注册点击事件for( var i=0;i < aList.length;i++){aList[i].addEventListener('click', function(e){//阻止a标签的默认行为e = e || window.event;e.preventDefault();//获取整个href路径//var target = this.href;//获取#片段识别符var target = this.hash;//获取box参照于body定位的top值var offsetTop = document.querySelector(target).offsetTop;//将页面跳转到对应的位置document.documentElement.scrollTop = offsetTop; });}
</script>
注意点:
**1. 这种方法url不会发生改变,因为我们阻止了a标签的默认行为.所以a标签不会跳转.
**2. document.querySelector(target).offsetTop;
$(target).offset().top 都是去求出盒子参照body定位对应的top值,这是因为offet家族的定义是:
如果元素自身是非固定定位,并且所有的父元素都没有定位,那么他的定位父级是body .
**3. 上面代码的target得到格式都是#box1,此时在原生中利用属性选择器来获取元素要很多.
document.querySelector(target) 等价于
document.querySelector('#box1')
2.3 第三种锚点定位的方法:
用js的srollIntoView方法 这是一个实验中的功能 此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合 使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器 中该功能的语法和行为可能随之改变。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head>
<style>ul {height: 200px;overflow-y: scroll;position: relative;}li {height: 30px;line-height: 30px;}
</style><body><ul><li>111</li><li>112</li><li>113</li><li>114</li><li>151</li><li>114541</li><li>11451</li><li>141411</li><li>11453411</li><li>112811</li><li>1124231</li><li>11446491</li><li>1233</li><li>111231231</li><li>11145645</li></ul>
</body>
<script>(function () {var li = document.querySelectorAll("li");var ul = document.querySelector("ul");var height =parseInt( getComputedStyle(document.querySelector("ul")).height );li.forEach(item => {item.onclick = function () {// this.style = "color:red"// 用自带的方法 但是如果父亲和爷爷都有滚动条的话,都会动// this.scrollIntoView(false)/* 1. scrollTop 小于0是不动的2. li 的offsetTop 是以dom 中的为准,是不会变的,通过滚动到试图中间只是视觉上变了,所以如果scollTop 等于 的offsetTop 就到最上面了3. top-height/2 所以说当到了中间的时候才会动*/let top=this.offsetTop;console.log('top',top);ul.scrollTop=top-height/2;}})})()
</script></html>
例子:Bootstrap框架: 模拟小风车科技官网_风铭大师的博客-CSDN博客
<template><div><div class="div"><ul class="navgator"><li class="navgatorLi" :class="{'isActive': index===navgatorIndex}" @click="handleLeft(index)" v-for="(item,index) in navgator" :key="item">{{item}}</li></ul><ul class="rightList"><li :id="'id'+index" v-for="(item,index) in listBox" :key="item">{{item}}</li></ul></div></div>
</template><script>export default {data() {return {navgator: ['列表A','列表B','列表C','列表D',],navgatorIndex: 0,listBox: ['A','B','C','D'],listBoxState: true,//点击导航栏时,暂时停止监听页面滚动};},created() {},mounted() {let timeId;window.addEventListener('scroll', () => {// 页面滚动停止100毫秒后才会执行下面的函数。clearTimeout(timeId);timeId = setTimeout(() => {this.scrollToTop();console.log('执行完成');}, 100);} , true);},methods: {// 点击导航菜单,页面滚动到指定位置handleLeft(index) {this.navgatorIndex = index;this.$el.querySelector(`#id${index}`).scrollIntoView({behavior: "smooth", // 平滑过渡block: "start" // 上边框与视窗顶部平齐。默认值});this.listBoxState=false;let timeId;clearTimeout(timeId);timeId = setTimeout(() => {this.listBoxState=true;},200);},// 监听页面元素滚动,改变导航栏选中scrollToTop() {// 获取视窗高度var domHight = document.body.offsetHeight;console.log(domHight)// dom滚动位置var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;if (this.listBoxState) {//作用是点击导航栏时,延迟这里执行。this.listBox.map((v,i) => {// 获取监听元素距离视窗顶部距离// var offsetTop = document.getElementById(`id${i}`).offsetTop;// 获取监听元素本身高度var scrollHeight = document.getElementById(`id${i}`).scrollHeight;// 如果 dom滚动位置 >= 元素距离视窗距离 && dom滚动位置 <= 元素距离视窗距离+元素本身高度// 则表示页面已经滚动到可视区了。if (scrollTop >= offsetTop && scrollTop<=(offsetTop+scrollHeight)) {// 导航栏背景色选中this.navgatorIndex = i;}})}},},
}
</script><style scoped>.div {width: 100%;background: #ededed;}.navgator {width: 200px;position: fixed;top: 0;}.navgator .navgatorLi {width: 100%;height: 1rem;display: flex;justify-content: center;align-items: center;border: 1px solid #ccc;border-top: none;}.navgator .isActive {color: #fff;background: darkseagreen;}.rightList {width: 560px;margin-left : 200px;}.rightList li {width: 100%;height: 10rem;display: flex;justify-content: center;align-items: center;border: 1px solid #ccc;}
</style>