需求:点击跳转时,页面呈现在内容部分
方法一: 通过路由
html
<h3 class="title" id="title">北京办公区</h3>
```html
js
mounted: function () {
// var hash = window.location.hash;
// var index = hash.lastIndexOf("#");
// if (index != -1) {
// var id = hash.substring(index + 1, hash.length + 1);
// var div = document.getElementById(id);
// if (div) {
// setTimeout(function () {
// console.log($(div).offset().top);
// //$('html,body').scrollTop($(div).offset().top - 43);
// $('html, body').animate({scrollTop: $(div).offset().top - 43}, 500)
// }, 500);
// }
// }
},```
路由跳转时 /tolist?#title即可
## 方法二
utils/ scrollTop.js
function setScrollTop(el,n=300) {
var T = document.getElementById(el);
let top = T.getBoundingClientRect().top; // console.log(;
window.scrollTo({
top: top-50 ,
behavior: "smooth",
});
}
export default setScrollTop;
js
引入
import setScrollTop from "../../utils/setScrollTop.js";
watch: {
$route(to, from) {
setScrollTop('title');
},
},
mounted(){
setScrollTop('title');
},
```html
html
<h3 class="title" id="title">北京办公区</h3>