DIV CSS 佈局教程網

jQuery 根据锚点 offset 值实现动画切换
編輯:JQuery特效代碼     

锚点相信大家都用过吧!但点击后那种生硬的直接跳转是不是让人有点不爽呢?下面分享一个小技巧,根据锚点的 offset 值来实现平滑的动画滚动切换,让页面定位更顺滑自然。

核心思路是拦截锚点链接的点击,读取目标元素的 offset().top,再用 animate 让页面平滑滚动到该位置:

 $(function(){
  $(".div_scoll a").click(function(){
    $("html,body").animate({ scrollTop:$($(this).attr("href")).offset().top + "px"},1000);
  });
});

完整代码如下,右侧固定了一列锚点按钮,点击即可平滑滚动到对应区块:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<style>
*{ margin:0; padding:0;}
.main{ width:1000px; margin:0 auto; position:relative; }
.main img{ float:left;}
.bg{ position:absolute; width:100%; z-index:-5;}
.bg01{ height:885px;background:url(../images/b_01.jpg) no-repeat center;}
.bg02{ height:938px;background:url(../images/b_04.jpg) no-repeat center; }
.bg03{ height:946px;background:url(../images/b_02.jpg) no-repeat center; }
.bg04{ height:946px;background:url(../images/b_03.jpg) no-repeat center; }
.div_scoll{ position:fixed; width:50px; height:200px; right:100px; top:50%;}
a{ display:block; background:#3F6; color:#000; width:50px; height:50px; }
</style>
</head>
<body>
<div class="wrapper">
  <div class="main">
    <div id="tab_01" class="tab"><img src="images/m_01.jpg" alt="" /></div>
    <div id="tab_02" class="tab"><img src="images/m_04.jpg" alt="" /></div>
    <div id="tab_03" class="tab"><img src="images/m_02.jpg" alt="" /></div>
    <div id="tab_04" class="tab"><img src="images/m_03.jpg" alt="" /></div>
  </div>
  <div class="bg">
    <div class="bg01" id="bg01"></div>
    <div class="bg02" id="bg02"></div>
    <div class="bg03" id="bg03"></div>
    <div class="bg04" id="bg04"></div>
  </div>
</div>
<div class="div_scoll">
  <a href="#bg01">图1</a>
  <a href="#bg02">图2</a>
  <a href="#bg03">图3</a>
  <a href="#bg04">图4</a>
</div>
<script>
$(function(){
  $(".div_scoll a").click(function(){
    $("html,body").animate({ scrollTop:$($(this).attr("href")).offset().top + "px"},1000);
  });
});
</script>
</body>
</html>

相比传统的锚点跳转,这种方式通过 1 秒的动画过渡,让页面滚动更加平滑优雅,大大提升了长页面导航的浏览体验。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved