2015-05-04 105 views
0

我正在構建一個單一頁面的web應用程序,當我點擊鏈接到同一頁面的div的錨定標記時,我不需要更改url。 div id被添加到網址中。請幫助如何在不更改網址的情況下導航到div。在不改變url的情況下導航到div

這是我到目前爲止的代碼:

$(document).ready(function() { 
 

 
\t 
 
\t $('a').on("click",function(e){ 
 
\t \t 
 
\t \t 
 
\t \t window.location="#link5" 
 
\t \t e.preventDefault(); 
 
\t \t e.stopPropagation(); 
 
\t \t console.log(window.location); 
 
\t \t 
 
\t }); 
 
})
#login { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
} 
 

 
a { 
 
    text-decoration: none; 
 
    display: inline-block; 
 
    padding-right: 15px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<a href="#">Link1</a> 
 
\t <a href="#">Link2</a> 
 
\t <a href="#">Link3</a> 
 
\t <a href="#">Link4</a> 
 
\t <a href="#">Link5</a> 
 

 
\t <h4>Content of the above links</h4> 
 
\t <div id="link1"> 
 
\t \t <h3>Contents of #link1</h3> 
 
\t \t <p>Sample contents placed in the div #link1</p> 
 
\t \t <p>Sample contents placed in the div #link1</p> 
 
\t \t <p>Sample contents placed in the div #link1</p> 
 
\t \t \t 
 
\t </div> 
 
\t <div id="link2"> 
 
\t \t <h3>Contents of #link2</h3> 
 
\t \t <p>Sample contents placed in the div #link2</p> 
 
\t \t <p>Sample contents placed in the div #link2</p> 
 
\t \t <p>Sample contents placed in the div #link2</p> 
 
\t 
 
\t </div> 
 
\t <div id="link3"> 
 
\t \t <h3>Contents of #link3</h3> 
 
\t \t <p>Sample contents placed in the div #link3</p> 
 
\t \t <p>Sample contents placed in the div #link3</p> 
 
\t \t <p>Sample contents placed in the div #link3</p> 
 
\t 
 
\t </div> 
 
\t <div id="link4"> 
 
\t \t <h3>Contents of #link4</h3> 
 
\t \t <p>Sample contents placed in the div #link4</p> 
 
\t \t <p>Sample contents placed in the div #link4</p> 
 
\t \t <p>Sample contents placed in the div #link4</p> 
 
\t \t <p>Sample contents placed in the div #link4</p> 
 
\t \t 
 
\t </div> 
 
\t <div id="link5"> 
 
\t \t <h3>Contents of #link5</h3> 
 
\t \t <p>Sample contents placed in the div #link5</p> 
 
\t \t <p>Sample contents placed in the div #link5</p> 
 
\t \t <p>Sample contents placed in the div #link5</p> 
 
\t \t <p>Sample contents placed in the div #link5</p> 
 
\t \t 
 
\t </div>

http://jsfiddle.net/vkarthikcse/3duv3ozz/3/

+2

可能的重複:http://stackoverflow.com/questions/6677035/jquery-scroll-to-element? – icke

回答

0

這應該工作:http://jsfiddle.net/3duv3ozz/4/

當然現在它是硬編碼到只有一個工作鏈接,但你應該明白:

$(document).ready(function() { 
    $('a').on("click",function(e){ 

     var posTop = $("#link5").offset().top; //Get the position of the element you want to scroll to 
     e.preventDefault(); 
     e.stopPropagation(); 
     $('html, body').scrollTop(posTop); //Scroll to that position 
     console.log(window.location); 

    }); 
}) 
1

$http://jsfiddle.net/xovd9c8t/2/

動畫,利用現代數據 - 元素

這會給你的平穩過渡,而導航到該頁面的一部分。用戶體驗將會非常棒。

+0

使用data- *而不是href完美地工作! – Kristine

相關問題