【问题标题】:scroll to certain div using url hashtag使用 url 标签滚动到某个 div
【发布时间】:2019-12-10 17:21:29
【问题描述】:

我有一个 vue 组件,它包含来自用户的回复。

因此,当用户回复评论时,操作会收到回复通知,并且通知的 URL 带有评论 ID,例如:url.com/post#c-900

如果用户点击链接,当用户点击链接时,我会尝试滚动到评论。

我尝试在答案中找到的刀片视图中使用此 Jquery sn-p:

 $(function() {
      // get hash value
      var hash = window.location.hash;
      // now scroll to element with that id
      $("html, body").animate({ scrollTop: $(hash).offset().top });
    });

回复 div:

  :id="'c-'+reply.id"

我该如何处理?因为页面加载时组件不会立即呈现。

我想不通。

帮助。

【问题讨论】:

    标签: javascript laravel vue.js


    【解决方案1】:

    如果组件没有立即渲染,我可以想到两个选择:

    1. 如果您可以访问加载组件的函数,请在加载组件时调用的回调函数中添加$("html, body").animate({ scrollTop: $(window.location.hash).offset().top });

    2. 如果您无权访问,可以尝试轮询该元素在 DOM 中是否存在。

    var hash, timeout = 0, poll = window.setInterval(function() {
      hash = $(window.location.hash);
    
      if (hash.length) {
        $("html, body").animate({ scrollTop: hash.offset().top });
        window.clearInterval(poll);
    
      } else if (timeout++ > 100) { // cancel the interval after 100 attempts (== 10s)
        window.clearInterval(poll);
      }
    }, 100);
    

    如果有人点击另一个链接,您需要先用clearInterval(poll) 清除当前的轮询功能,然后再设置一个新的。

    【讨论】:

    • 嗯,可以,但是如果我向下滚动然后向上滚动>刷新页面,它将滚动到 div,页面加载后将返回顶部
    【解决方案2】:

    您可以在回复组件中为您的 div like this 创建一个引用。假设您的参考名称是“yourdiv”。然后在 "mounted" 钩子中你可以做这样的事情:

    const hash = window.location.hash
    if(hash === reply.id) {
        const distanceFromTop = this.$refs.yourdiv.getBoundingClientRect().top
        window.scrollTo({
          top: distanceFromTop,
          behavior: 'smooth',
        })
    }
    

    How to use refs to access your application DOM in Vue.js

    【讨论】:

    • 我没有使用 vue-router
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多