页面全屏垂直平滑滚动代码实例
本章节分享一段代码实例,它实现了网页全屏垂直滚动效果。
并且详细介绍一下它的实现过程,需要的朋友可以做一下参考。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> body { margin: 0; height: 100%; overflow:hidden; } #a111 { position: fixed; width: 1000px; left: 10%; } #a111 a { display: block; width: 150px; height: 20px; background: #000; color: #fff; float: left; } #a111 a:hover { background: #f60; } #b11 { height: 1000px; background: #090; } #b22 { height: 1000px; background: #fc0; } #b33 { height: 1000px; background: #09d; } </style> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script type="text/javascript"> (function ($) { $.extend($.fn, { scrollTo: function (time, to) { time = time || 800; to = to || 1; $('a[href*=#]', this).click(function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[id=' + this.hash.slice(1) + ']'); if ($target.length) { if (to == 1) { $('html,body').animate({ scrollTop: $target.offset().top }, time); } else if (to == 2) { $('html,body').animate({ crollLeft: $target.offset().left }, time); } else { alert('argument error'); } return false; } } }); } }); })(jQuery); $(function () { $("#a111").scrollTo(700) }); </script> </head> <body> <div id="a111"> <a href="#b11">前端教程网一</a> <a href="#b22">前端教程网二</a> <a href="#b33">前端教程网三</a> </div> <div id="b11">页面一</div> <div id="b22">页面二</div> <div id="b33">页面三</div> </body> </html>
上面的代码实现了我们的要求,下面介绍一下它的实现过程。
一.代码注释:
(1).(function ($) {})(jQuery),匿名自执行函数,传递的是jQuery对象。
(2).$.extend($.fn, {}),扩展$.fn对象。
(3).scrollTo: function (time, to) {},此方法实现了平滑滚动效果,time规定动画执行的时间,to表示滚动的方位,如果是1,那么就是垂直滚动,如果是2,那么就是水平滚动。
(4).time = time || 800,如果传递了time,那么就使用传递的参数,否则默认值是800毫秒。
(5).to = to || 1,如果传递了to,那么就用传递的参数,否则默认值是1。
(6).$('a[href*=#]', this).click(function () {}),为href属性值baohan#的链接a元素注册click事件处理函数。
(7).if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname),location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 是用来判断是否是当前页面锚点定位,location.hostname == this.hostname是用来验证是否是同域。
(8).var $target = $(this.hash),获取链接的锚点部分也就是#和#号的后面的部分。
(9).$target = $target.length && $target || $('[id=' + this.hash.slice(1) + ']'),判断是否存在锚点部分,如果存在那么就获取和id对应的元素对象。(10).if ($target.length) {},如果存在指定对象。
(11).if (to == 1) {
$('html,body').animate({
scrollTop: $target.offset().top
}, time);
},进行垂直滚动效果,滚动的尺寸就是指定元素offset().top值。
二.相关阅读:
(1).location.pathname可以参阅location.pathname一章节。
(2).replace()可以参阅正则表达式replace()函数一章节。
(3).slice()可以参阅javascript slice() 一章节。
(4).animate()方法可以参阅jQuery animate()一章节。
(5).offset()方法可以参阅jQuery offset()一章节。