gpt4 book ai didi

Jquery 偏移量返回错误值

转载 作者:行者123 更新时间:2023-12-01 00:40:35 24 4
gpt4 key购买 nike

我有一个折叠的侧边栏(使用 Bootstrap ),并且我正在尝试确保折叠的侧边栏只要元素可见,就会滚动到该元素。

为了做到这一点,我使用 jQuery 的 offset() ,它在第一次点击时返回 0并在第二次单击时返回正确的偏移量。

这是我的代码:

    $.each($('[data-toggle="collapse"]'), function() {
$(this).on("click", function() {
if ($(this).is('A')) {
event.preventDefault(); $(this).toggleClass("active");
var x = $(this).attr("href");
console.log($(x).offset().top)

}
})
})

最佳答案

设置为 display: none 的项目位于页面流之外,这意味着它们不占用页面内的空间。这意味着虽然它们设置为 display: none,但它们没有偏移值。

第一次单击时,浏览器会尝试查找偏移量(0),然后显示该元素。一旦显示元素,就会给出左/上偏移值。

Example Fiddle

关于Jquery 偏移量返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862921/

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