问题
I have a navigation menu: Intro, Size, Play, Food. When a user click on the hyper link of the menu item, I want to navigate to that element and animate.
For example, if a user click on the Size menu item, then I want to animate & scroll down to the item with id="Size".
Note: Here size menu item href does not have any value, because it is a dynamic.
index.html
<nav>
<ul>
<li><a href="#">Intro</a></li>
<li><a href="#">Size</a></li>
<li><a href="#">Play</a></li>
<li><a href="#">Food</a></li>
</ul>
<div class="clear"></div>
</nav>
<aside id="Size" class="sidebar">
<h3>Size</h3>
<img src="Images/boxer2.jpg" />
<p>Hegyét bár érti szeret.
</p>
</aside>
回答1:
You can perform smooth scrolling using $.animate(...) by passing the offset position of the element to scrollTop.
$.animate:http://api.jquery.com/animate/
HTML CODE:
<nav>
<ul>
<li><a href="#">Intro</a>
</li>
<li><a href="#">Size</a>
</li>
<li><a href="#">Play</a>
</li>
<li><a href="#">Food</a>
</li>
</ul>
<div class="clear"></div>
</nav>
<aside id="Intro" class="sidebar">
<h3>Intro</h3>
<img src="Images/boxer2.jpg" />
<p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Size" class="sidebar">
<h3>Size</h3>
<img src="Images/boxer2.jpg" />
<p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Play" class="sidebar">
<h3>Play</h3>
<img src="Images/boxer2.jpg" />
<p>Hegyét bár érti szeret.</p>
</aside>
<aside id="Food" class="sidebar">
<h3>Food</h3>
<img src="Images/boxer2.jpg" />
<p>Hegyét bár érti szeret.</p>
</aside>
JQUERY CODE:
$('li a').on('click', function (e) {
var targetSec = $(this).text();
$('html, body').animate({
scrollTop: $('#' + targetSec).offset().top
}, 2000);
});
LIVE DEMO:
http://jsfiddle.net/dreamweiver/3Xm48/11/
Happy Coding:)
回答2:
You'll want to do something like this
$("nav ul li").click(function() {
var liText = $(this).text();
$('html, body').animate({
scrollTop: $("#" + liText ).offset().top
}, 1000);
});
来源:https://stackoverflow.com/questions/22069971/on-menu-clicked-animate-scroll-to-the-element-dynamically