滚动顶部 - 替代preventDefault()函数

时间:2014-07-16 17:53:16

标签: javascript jquery scroll

我的脚本中的preventDefault()函数(参见实例http://jsfiddle.net/E6MQd/)在某些情况下会导致附带问题。我怎样才能调整我的代码以摆脱它?

编辑:我应该更具体一点。当我说抵押问题时,我的意思是阻止打开一个精美的盒子弹出窗口。请看这里http://goo.gl/cZgzqq(链接到时事通讯花式框的链接位于提交按钮下方页面的底部 - 点击它时没有任何反应)

非常感谢,

//==============
//! Smooth scrolling
//==============

$(document).ready(function(e) {
$('a[href*=#]:not([href=#])').click(function (ev) { // Added 'ev' parameter
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            ev.preventDefault(); // We're animating this, so don't let the browser try to navigate to this URL
            $('html,body').animate({
                scrollTop: target.offset().top - 100
            }, 'normal');
        }
    }
});


window.onscroll = scrollFunction;
function scrollFunction() {
    var doc = document.documentElement, body = document.body;
    var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);
    if (top > 200) {
        $('.back-to-top').fadeIn();
    }
    else {
        $('.back-to-top').fadeOut();
    }
}
});

1 个答案:

答案 0 :(得分:1)

既然你没有说出问题所在。我的猜测是问题是你的“回到顶部”不是动画。以下是解决方案:

$('a[href*=#]').click(function (ev) {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname)
    {
       var target = $(this.hash);
       target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
       ev.preventDefault();

       if (target.length) { //this is for going to contact page
          $('html,body').animate({
              scrollTop: target.offset().top - 100
          }, 'normal');
       }
       else{ //this is for going to the top
           $('html,body').animate({
               scrollTop: 0
           }, 'normal');
       }
    }
});

JSFiddle