jQuery从按钮onclick跳转或滚动到页面上的某个位置、div或目标 [英] jQuery jump or scroll to certain position, div or target on the page from button onclick

查看:27
本文介绍了jQuery从按钮onclick跳转或滚动到页面上的某个位置、div或目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击一个按钮时,我希望能够向下跳或滚动到页面上的特定 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
});

我该怎么做?

推荐答案

我会将链接的样式设置为看起来像一个按钮,因为这样没有 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.

原始示例:

jsfiddle

$(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 类更改为 .button 并添加了 css 样式以使链接看起来像按钮之外,一切都基本相同.

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从按钮onclick跳转或滚动到页面上的某个位置、div或目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆