js页面滚动,设置锚点,控制页面滚动到某个节点位置

45 篇文章 1 订阅

1.获取某Dom元素,距离其上级为position:relation元素的顶部距离
元素在上级为position:relation元素里的坐标 - 页面滚动的距离
获取元素距离relation元素顶部的距离 = dom.ofisetTop - window.pageYOffset;
元素自身的高度:dom.offsetHelght;
2.页面滚动
const dom = document.getElementByld(`${id}`)
window.scrollTo({
  top: dom.offsetTop, //需要滚动的距离
  behavior: 'smooth',
})

react监听鼠标滚轮事件 -> 锚点按钮状态
const handleScroll = (e)=>{ }
componentDidMount(){
  //监听火狐鼠标滚动事件
  document.addEventListener("DOMMouseScrol", handleScroll, false);
  //监听谷歌苹果浏览器滚动事件
  document.addEventListener("mousewheel", handleScroll, false);
}
componentWillUnmount(){
 document.removeEventListener("DOMMouseScroll", handleScroll);
 document.removeEventListener("mousewheel", handleScroll);
}

3. 判断 某个元素是否滚动到某个位置范围时,才显示数据。

const [show, setShow] = useState(false)

const judgeDistanceTop =()=> {
 let dom= document.getElementById('home_content_statistic');
 if (anchorElement) {
  // 判断元素距离顶部的滚动距离范围。
  const scrollDistance = dom.offsetTop - window.pageYoffset;
  if (scrollDistance > -100 && scrollDistance <= 460) {
    setShow(true);
  }
 }
}
/**
* 模拟鼠标滚轮事件触发
*/
useEffect(()=> {
  const timer = setInterval(()=>{ judgeDistanceTop()}, 100)
  return ()=>{
    clearInterval(timer)
  }
}, [])

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值