gpt4 book ai didi

javascript - 使用 url 标签滚动到某个 div

转载 作者:行者123 更新时间:2023-12-03 06:48:26 25 4
gpt4 key购买 nike

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

因此,当用户回复评论时,op 会收到回复通知,并且通知的 URL 的评论 ID 为:url.com/post#c-900 .

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

我试图在我在一个答案中找到的 Blade View 中使用这个 Jquery 片段:

 $(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"

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

我想不通。

帮助。

最佳答案

如果组件没有立即呈现,我可以想到两个选项:

  • 如果您有权访问加载组件的函数,请添加 $("html, body").animate({ scrollTop: $(window.location.hash).offset().top });加载组件时调用的回调函数。
  • 如果您无权访问,您可以尝试轮询元素在 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) 清除当前的轮询功能。在设置新的之前。

    关于javascript - 使用 url 标签滚动到某个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59272487/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com