jQuery从button onclick跳转或滚动到页面上的某个位置,div或目标 [英] jQuery jump or scroll to certain position, div or target on the page from button onclick
问题描述
当我点击按钮时,我想能够跳下或滚动到页面上的特定div或目标。
When I click on a button i want to be able to jump down or scroll to a specific div or target on the page.
$('#clickMe').click(function() {
//jump to certain position or div or #target on the page
});
我该如何做?
推荐答案
我会将链接设置为类似按钮,因为这种方式有一个no-js后备。
I would style a link to look like a button, because that way there is a no-js fallback.
所以这是你如何使用jquery动画跳转。 No-js fallback是没有动画的正常跳跃。
So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.
原始示例:
$(document).ready(function() {
$(".jumper").on("click", function( e ) {
e.preventDefault();
$("body, html").animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
});
});
#long {
height: 500px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Links that trigger the jumping -->
<a class="jumper" href="#pliip">Pliip</a>
<a class="jumper" href="#ploop">Ploop</a>
<div id="long">...</div>
<!-- Landing elements -->
<div id="pliip">pliip</div>
<div id="ploop">ploop</div>
新示例与实际按钮样式的链接,只是为了证明一个点。
New example with actual button styles for the links, just to prove a point.
除了我将 .jumper
更改为后,一切都基本相同。
Everything is essentially the same, except that I changed the class .jumper
to .button
and I added css styling to make the links look like buttons.
这篇关于jQuery从button onclick跳转或滚动到页面上的某个位置,div或目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!