我正在构建单页面Web应用程序,在单击链接到同一页面中的div的锚标记时,我不需要更改URL。 div id被添加到url中。请帮助您在不更改网址的情况下导航到div。
到目前为止,这是我的代码:
$(document).ready(function () {
$('a').on("click",function(e){
window.location="#link5"
e.preventDefault();
e.stopPropagation();
console.log(window.location);
});
})
#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>
<a href="#">Link2</a>
<a href="#">Link3</a>
<a href="#">Link4</a>
<a href="#">Link5</a>
<h4>Content of the above links</h4>
<div id="link1">
<h3>Contents of #link1</h3>
<p>Sample contents placed in the div #link1</p>
<p>Sample contents placed in the div #link1</p>
<p>Sample contents placed in the div #link1</p>
</div>
<div id="link2">
<h3>Contents of #link2</h3>
<p>Sample contents placed in the div #link2</p>
<p>Sample contents placed in the div #link2</p>
<p>Sample contents placed in the div #link2</p>
</div>
<div id="link3">
<h3>Contents of #link3</h3>
<p>Sample contents placed in the div #link3</p>
<p>Sample contents placed in the div #link3</p>
<p>Sample contents placed in the div #link3</p>
</div>
<div id="link4">
<h3>Contents of #link4</h3>
<p>Sample contents placed in the div #link4</p>
<p>Sample contents placed in the div #link4</p>
<p>Sample contents placed in the div #link4</p>
<p>Sample contents placed in the div #link4</p>
</div>
<div id="link5">
<h3>Contents of #link5</h3>
<p>Sample contents placed in the div #link5</p>
<p>Sample contents placed in the div #link5</p>
<p>Sample contents placed in the div #link5</p>
<p>Sample contents placed in the div #link5</p>
</div>
答案 0 :(得分:1)
答案 1 :(得分: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);
});
})