在不改变url的情况下导航到div
问题描述:
我正在构建一个单一页面的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/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);
});
})
可能的重复:http://stackoverflow.com/questions/6677035/jquery-scroll-to-element? – icke