javascript - 我的 javascript 平滑滚动无法滚动到 Firefox 中的正确位置,有人知道我做错了什么吗?

标签 javascript jquery html firefox smooth-scrolling

我正在构建一个单页网站,我需要导航链接来平滑滚动到网站的不同页面或部分。我使用的 javascript 在 Chrome 和 Safari 中完美运行,但在 FireFox 中,它无法滚动到正确的位置。我的所有 anchor 都在 html 中,但这是我正在使用的 javascript。我在 Firefox 兼容性方面缺少什么吗?

<!-- SMOOTH SCROLL -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
                $(".contactLink").click(function(){
                    if ($("#contactForm").is(":hidden")){
                        $("#contactForm").slideDown("slow");
                    }
                    else{
                        $("#contactForm").slideUp("slow");
                    }
                });
            });
            function closeForm(){
                $("#messageSent").show("slow");
                setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
           }

$(document).ready(function() {
  function filterPath(string) {
    return string
      .replace(/^\//,'')
      .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
      .replace(/\/$/,'');
  }
  $('a[href*=#]').each(function() {
    if ( filterPath(location.pathname) == filterPath(this.pathname)
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
      var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
      var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
       if ($target) {
         var targetOffset = $target.offset().top;
         $(this).click(function() {
           $('html, body').animate({scrollTop: targetOffset}, 1000);
           var d = document.createElement("div");
        d.style.height = "101%";
        d.style.overflow = "hidden";
        document.body.appendChild(d);
        window.scrollTo(0,scrollToM);
        setTimeout(function() {
        d.parentNode.removeChild(d);
            }, 10);
           return false;
         });
      }
    }
  });
});

最佳答案

试试这个:

$(".anchor").click(function(e) {
    e.preventDefault();
    anchor = $(this).attr('href');
    $("html, body").animate({
      'scrollTop':   $(anchor).offset().top
    }, 1000);
});

适用于像

这样的 anchor
<a class="anchor" href="#div1">click</a>

<div id="div1">texttext</div>

DEMO

关于javascript - 我的 javascript 平滑滚动无法滚动到 Firefox 中的正确位置,有人知道我做错了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895406/

相关文章:

javascript - 使用 jquery 动态添加时 Selectric 不工作

javascript - 为什么从函数返回的 Promise 解析为从该函数内的 .then 返回的值

javascript - Internet Explorer 呈现通过 JavaScript 生成的表格的速度很慢

javascript - 如何循环和替换元素内的字符

javascript - 默认情况下,如果焦点移至jquery datepicker,则不会激活它

html - 我如何在 css 中水平居中 div 元素?

javascript - 每次打开模态窗口时重新加载模态体

javascript - 在嵌套调用中使用 clearInterval

javascript - 如何隐藏我的下拉菜单?

html - CSS 裁剪或缩放图像到 100% 宽度的 DIV