使用 URL 主题标签滚动到某个 div



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

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

如果用户单击链接,当用户单击链接时,我正在尝试滚动到评论。

我尝试在答案中找到的刀片视图中使用此 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"

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

我想不通.

帮助。

如果不立即渲染组件,我可以想到两个选项:

  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 创建一个引用。假设您的参考名称是"您的迪夫"。然后在"挂载"钩子中,您可以执行以下操作:

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

如何使用 refs 在 Vue 中访问你的应用程序 DOM.js

最新更新