您的位置:首页 > 教程笔记 > 前端笔记

点击可以平滑定位到网页指定位置

2023-12-04 13:40:27 前端笔记 185

其实就是比较人性化的锚点效果,点击能够以平滑的方式定位到网页的指定位置。

并不像是默认的锚点功能瞬间到达的效果。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $("a.topLink").click(function() {
    $("html, body").animate({
      scrollTop: $($(this).attr("href")).offset().top + "px"
    }, {
      duration: 500,
      easing: "swing"
    });
    return false;
  });
});
</script>
</head>
<body>
<div id="anchor">实例</div>
<p><a href="#anchor" class="topLink">点击定位</a></p>
</body>
</html>

上面的代码实现了平滑定位效果,下面介绍一下它的实现过程。

一.代码注释:

(1).$(document).ready(function(){}),当文档结构完全加载完毕再去执行函数中的代码。

(2).$("a.topLink").click(function() {}),为class属性值为topLink的链接<a>元素注册click事件处理函数。

(3).$("html, body").animate({

    scrollTop: $($(this).attr("href")).offset().top + "px"

  }, {

    duration: 500,

    easing: "swing"

  });

  return false;

}),以动画方式实现了定位效果。

$($(this).attr("href")).offset().top,链接的href属性值就是div元素的id属性值。

$($(this).attr("href"))获取div元素。

$($(this).attr("href")).offset().top,获取div元素距离顶部的距离。

(4).return false,取消点击链接的跳转效果。

相关推荐