JavaScript上下滚动不可预测

JavaScript scrolling unpredictable up and down

本文关键字:不可预测 滚动 上下 JavaScript      更新时间:2023-09-26

我遇到了一个大问题或小问题。我正在尝试滚动我的网站,所以每个容器都会滑动到网站顶部的特定位置。但是,就我所见,这是一个问题,因为如果你点击第一个项目,然后点击下一个项目,脚本会滚动到相同的位置,但如果你点击上一个项目上方的项目,它会滚动到页面底部。

我的脚本是一个简单的锚脚本,看看:

$("a.scrollForMe").each(function() {   // go through all links
var href = $(this).attr("href");
if (typeof(href) == "undefined") { return; }
if ($(this).attr("href").match(/^#/)) {   // if href starts with #
    $(this).click(function() {  // add a click event to it
        var name = $(this).attr("href").substring(1);  // get the anchor link
        // on click, scroll to the a with a name attribute matching the anchor
        $('html, body').animate({scrollTop: $("section[name='" + name + "']").offset().top - 420}, 1000);
        //alert ("This height is: " + $("section[name='" + name + "']").height() + " and it's name is " + name);
    });
}
});

如果你想看看目前的工作情况,请查看我的网站:http://1st-issue.de/2012/redaxo/#sec10

我希望你能帮助我!提前感谢!

如果使用此代码可能会更好。我在保存页面上进行了测试。

$(document).ready(function() {
  $("a.scrollForMe").each(function() {   // go through all links
    var href = $(this).attr("href");
    if (typeof(href) == "undefined") { return; }
    if (href.match(/^#/)) {   // if href starts with #
      $(this).click(function() {  // add a click event to it
        var name = href.substring(1);  // get the anchor link
        // on click, scroll to the a with a name attribute matching the anchor
        $('html, body').animate({scrollTop: $("section[name='" + name + "']").prevAll("section").first().offset().top + 100 }, 1000);
        //alert ("This height is: " + $("section[name='" + name + "']").height() + " and it's name is " + name);
      });
    }
  });
});

如果我能给你一个建议,你不应该使用href来锚定,因为屏幕会自动跳转到锚定。使用您添加的代码,屏幕会闪烁,因为浏览器会转到相应的锚点,然后执行scrollTop动画。但这只是一个建议。