关于vue 和react 中的hash与锚点冲突问题

本文介绍了一种使用事件委托处理Hash与锚点冲突的方法,通过正则表达式匹配锚点,实现页面平滑滚动,避免了点击a标签时location.href被替换的问题。
  // 可以利用事件委托进行处理hash和锚点的冲突问题。
  // 
  handleAnchorClick(e){
    if (e.target && e.target.tagName.toLowerCase() === 'a') {
      // 确定点击元素是不是a元素;
      // Determine whether the click element is a element;
      const href = e.target.href;
      // 确定你的锚点href
      const regx = /#锚点名字\/.+/g;
       // 指定符合你锚点的正则表达式
      //  Specify regular expressions that match your anchor
      const result = regx.exec(href);
      // 检测是否可以匹配到你的锚点
      // Check if it matches your anchor
      if (result && result.length === 1 ) {
        const name = result[0].replace('#','');
        // 替换锚点链接中#
        // Replacement anchor link#
        document.querySelector(`a[name="${decodeURI(name)}"]`).scrollIntoView();
        // 拿到你的锚点元素并移动到锚点的位置
        // Get your anchor element and move to the anchor position
        e.preventDefault();
        // 阻止点击带来替换location.href的问题
        // Blocking clicks raises the issue of replacing location. href
      }
    }
  }

 

转载于:https://www.cnblogs.com/l8l8/p/11276068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值