进入html页面自动锁定锚点,如何将HTML页面滚动到给定的锚点?

Илья Зеленьк..

20

2018年纯粹的js:

滚动到元素有一种非常方便的方法:

el.scrollIntoView({

behavior: 'smooth', // smooth scroll

block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.

})

但据我了解,他没有下面的选项那么好的支持.

f04e859ab16a2d51f030655c225da8a3.png

如果元素必须在顶部:

const element = document.querySelector('#element')

const top = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({

top, // scroll so that the element is at the top of the view

behavior: 'smooth' // smooth scroll

})

如果您希望元素位于中心:

const element = document.querySelector('#element')

const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)

const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({

top: rect.top + rect.height / 2 - viewHeight / 2,

behavior: 'smooth' // smooth scroll

});

支持:

73e2880d3487f1b2fe0ff360b6e1beac.png

他们写scroll的方法与方法相同scrollTo,但支持显示更好scrollTo.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值