导航到div而不更改URL

时间:2015-05-04 09:45:15

标签: javascript html5

我正在构建单页面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>

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

2 个答案:

答案 0 :(得分:1)

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

使用动画,使用现代数据元素

这将在您导航到页面的该部分时为您提供平滑过渡。用户体验将是惊人的。

答案 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);

    });
})