2014-02-26 38 views
2

我对jQuery非常陌生,并且试图在我的web项目上实现平滑滚动到div。出于某种原因,当我创建一个新的基本html测试页面并为滚动添加js时,它可以工作。但是,当我将完全相同的代码导入到我的主项目中时,它实际上并不滚动,而是在轻微暂停后直接跳到目标div。我不知道为什么它可以在测试页面上工作,而不是在我的实际项目中。有没有人有什么想法会导致它做到这一点?任何帮助将非常感激!谢谢。jQuery平滑滚动锚定问题

我在头部形成以下脚本:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> 
<script src="js/script.js"></script> 

的HTML:

<div id="mainContent"> 
    <section id="splash"> 
     <div class="banner"> 

     </div> 

     <div id="intro"> 
      <h1>Heading 1</h1> 
      <h2>Heading 2</h2> 
      <a href="#productInfo">LEARN MORE</a> 
     </div> 

    </section> 

    <div id="productInfo"> 
      </div> 

和里面的script.js:

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

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

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

我在http://jsbin.com/创建了一个快速JSBin quraxano/1 /编辑,也许你可以添加一些你的其他代码,看看它是否仍然如预期的那样,然后我可以帮助诊断问题。另一种选择可能是尝试在http://demos.flesler.com/jquery/scrollTo/中插入此代码并查看它是否适用于您的代码。 – click2install

回答

0

fiddle

做到了

下面是代码,

HTML:

<section id="splash"> 
    <div class="banner"></div> 
    <div id="mainContent"> 
     <div id="intro"> 
      <h1>Heading 1</h1> 
      <h2>Heading 2</h2> 
      <a href="#productInfo">LEARN MORE</a> 
     </div> 
    </div> 
</section> 
<div id="productInfo">test tests</div> 

CSS:

#productInfo { background:gray; color:#000; margin-top:400px; padding:10px; height:1000px;} 

的jQuery:

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

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

    }); 
}); 
});