2016-06-10 102 views
0

所以,我正在製作一個網頁,並希望使用jQuery在其中包含一些平滑滾動。問題是我的代碼不工作,當我點擊鏈接時,頁面直接跳轉到現場,而不是平滑滾動。下面的代碼的relevat部分 -jQuery - 平滑滾動代碼不工作

HTML -

<script src="scroll.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> 
</head> 
<body> 
<div id="sec1"> 
    <span id="header">Heading</span> 
    <!--<span id="notheader">Umesh meena is the coolest</span>--> 
    <!--<div id="navbar" class="before">lol</div>--> 
    <a href="#sec2" id="button1" >link to the page</a> 
</div> 
<div id="sec2"> 
    <span id="main">lorem</span> 
</div> 
</body> 
</html> 

SCROLL.js文件 -

$(document).ready(function(){ 
    $('a[href^="#"]').on('click',function (e) { 
     e.preventDefault(); 

     var target = this.hash; 
     var $target = $(target); 

     $('html, body').stop().animate({ 
      'scrollTop': $target.offset().top 
     }, 900, 'swing', function() { 
      window.location.hash = target; 
     }); 
    }); 
}); 
從這個

除了我有另一個JavaScript文件的鏈接(這我不應該認爲應該干涉請幫助/建議選項

回答

1

$(document).ready(function() { 
 
    $('a[href^="#"]').click(function(e) { 
 
    e.preventDefault(); 
 

 
    var target = this.hash; 
 
    var $target = $(target); 
 

 
    if ($target.length === 0) { 
 
     alert('No target!'); 
 
     return; 
 
    } 
 
    
 
    $('html, body').animate({ 
 
     scrollTop: $target.offset().top 
 
    }, 900, 'swing', function() { 
 
     window.location.hash = target; 
 
    }); 
 
    }); 
 
});
div[id*="sec"] { 
 
    margin-bottom: 500px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="sec1"> 
 
    <span id="header">Heading</span> 
 
    <!--<span id="notheader">Umesh meena is the coolest</span>--> 
 
    <!--<div id="navbar" class="before">lol</div>--> 
 
    <a href="#sec2" id="button1">link to the page</a> 
 
    <a href="#sec3" id="button2">link to the page</a> 
 
    <a href="#sec4" id="button3">link to no target</a> 
 
</div> 
 
<div id="sec2"> 
 
    <span id="main">lorem</span> 
 
</div> 
 
<div id="sec3"> 
 
    <span id="main">ipsum</span> 
 
</div> 
 
<div id="notarget"> 
 
    <span id="main">Vous aved un chat.</span> 
 
</div>