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

Scroll top - alternative to preventDefault() function

本文关键字:preventDefault 函数 滚动 顶部      更新时间:2023-09-26

下面脚本中的preventDefault()函数(参见实际示例http://jsfiddle.net/E6MQd/)在某些情况下会导致附带问题。我如何调整我的代码来摆脱它?

Edit:我应该说得更具体一些。当我说附带问题时,我指的是防止打开一个花哨的弹出框。见这里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();
    }
}
});

既然你没有说问题是什么。我猜问题是你的"重回巅峰"不够生动。下面是解决方案:

$('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