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

我心飞翔 分类:实例代码

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

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

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style>
#anchor{
  width:100px;
  height:1300px;
  background:#ccc;
  text-align:center;
  margin:0px auto;
  margin-top:200px;
}
p{
  position:fixed;
  width:100px;
  height:100px;
  background:#ccc;
  text-align:center;
  right:0px;
  bottom:10px;
}
</style>
<script src="http://libs.baidu.com/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,取消点击链接的跳转效果。

二.相关阅读:

(1).animate()可以参阅jQuery animate()一章节。

(2).attr()方法可以参阅jQuery attr()一章节。

(3).offset()方法可以参阅jQuery offset()一章节。

(4).scrollTop属性可以参阅scrollTop一章节。

回复

我来回复
  • 暂无回复内容