单击链接后,如何使链接不滚动到首页? [英] How do you make the link doesn't scroll you at the top page after clicking it?

查看:97
本文介绍了单击链接后,如何使链接不滚动到首页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSFiddle上有以下代码

I have the following code on JSFiddle

https://jsfiddle.net/ddy3353q/3/

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        event.preventDefault();
      }
    }
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome-animation/0.0.10/font-awesome-animation.min.css">

</head>

<body>
  <div style="background-color:red; height: 1000px">
    LINK AT THE BOTTOM
  </div>
  <div class="collapse" id="work-exp-collapse">

    <div>TEST HIDDEN DIV HELLO!!</div>

  </div>
  <div style="margin: 0 auto; text-align: center; display: block">
    <i aria-hidden="true" class="fa fa-chevron-down yarrow"></i>  <a aria-controls="work-exp-collapse" aria-expanded="false" class="aa-gray-line SeeMore2" data-toggle="collapse" href="#work-exp-collapse">view more experience</a>
  </div>

</body>
<!-- JS code -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<!-- Recpatcha Google -->
<script src="https://www.google.com/recaptcha/api.js">
</script>
<!--JS below-->

</html>

我想知道如何避免单击链接时它自动在页面顶部滚动屏幕,而不是停留在隐藏div出现的相同位置.

I wonder how I could make it to avoid when you click on the link it automatically scroll your screen at the top of the page instead of stay at the same position where the hidden div appear.

谢谢

推荐答案

由于未显示target元素,因此target.offset().top0.

Caused the target element is not shown yet, thus target.offset().top is 0.

只需等待通过听shown.bs.collapse(由Boostrap解雇,链接)显示隐藏的div,然后执行您的滚动.

Just wait for the hidden div to be shown by listening shown.bs.collapse (fired by Boostrap, link) and do your scroll.

  if (target.length) {
    target.one('shown.bs.collapse', function() {        
       $('html, body').animate({
         scrollTop: target.offset().top
       }, 1000);
    });
    event.preventDefault();
  }

演示: https://jsfiddle.net/ddy3353q/5/

这篇关于单击链接后,如何使链接不滚动到首页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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