平滑滚动链接与锚 [英] Smooth scroll for link with anchor

查看:46
本文介绍了平滑滚动链接与锚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找如何为 example.com/subpage#anchor 等链接添加平滑滚动的方法.
我正在尝试使用此代码

 $(document).on('click', 'a[href^="#"]', function (event) {event.preventDefault();$('html, body').animate({scrollTop: $($.attr(this, 'href')).offset().top}, 500);});

但它不适用于 example.com/subpage#anchor

解决方案

实际上,您的逻辑看起来运行良好,无需任何修改.

$(document).on('click', 'a[href^="#"]', function(event) {event.preventDefault();$('html, body').animate({scrollTop: $($.attr(this, 'href')).offset().top}, 500);});

#container menu {位置:固定;顶部:0;左:0;右:0;边距:0;填充:0;背景颜色:RGB(128、128、128);}菜单里{显示:内联块;最小宽度:32.75%;文本对齐:居中;背景颜色:rgb(152, 152, 152);}#家,#关于我们,#接触 {显示:块;最小高度:600px;}#家 {背景颜色:红色;边距顶部:19px;}#关于我们 {背景颜色:绿色;}#接触 {背景颜色:蓝色;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="容器"><菜单><li><a href="#home">首页</a></li><li><a href="#aboutUs">关于我们</a></li><li><a href="#contact">联系我们</a></li></菜单><div id="home"></div><div id="aboutUs"></div><div id="联系人"></div>

I'm looking for way how to add smooth scroll for link like example.com/subpage#anchor.
I'm trying to used this code

 $(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top 
    }, 500);
});

but it does not work for example.com/subpage#anchor

解决方案

Actually, your logic appear to run fine without any modification.

$(document).on('click', 'a[href^="#"]', function(event) {
  event.preventDefault();

  $('html, body').animate({
    scrollTop: $($.attr(this, 'href')).offset().top
  }, 500);
});

#container menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: 0;
  padding: 0;
  background-color: rgb(128, 128, 128);
}

menu li {
  display: inline-block;
  min-width: 32.75%;
  text-align: center;
  background-color: rgb(152, 152, 152);
}

#home,
#aboutUs,
#contact {
  display: block;
  min-height: 600px;
}

#home {
  background-color: red;
  margin-top: 19px;
}

#aboutUs {
  background-color: green;
}

#contact {
  background-color: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <menu>
    <li><a href="#home">Home</a></li>
    <li><a href="#aboutUs">About Us</a></li>
    <li><a href="#contact">Contact Us</a></li>
  </menu>

  <div id="home"></div>
  <div id="aboutUs"></div>
  <div id="contact"></div>
</div>

这篇关于平滑滚动链接与锚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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