每次浏览网站右下角都会返回页面顶部的按钮,每次都会点击一下,其实这是为了更好的用户体验而设置的,今天小猿圈web前端讲师教你用jQuery做个返回顶部按钮。
我们先来分析一下具体流程 当页面没有滚动的时候,这个按钮是隐藏状态,当向下滚动1000px时这个按钮会以淡入的效果出现,这时候点击按钮会返回顶部,并且按钮会隐藏。 首先我们来简单布局一下页面,这里就不用多讲解了,直接放一个我的HTML和CSS源码。 <body> <div style="width:700px; margin: 0 auto;"> <img src="6.png" alt=""> <img src="2.jpg" alt=""> <img src="3.jpg" alt=""> <img src="4.jpg" alt=""> <img src="5.jpg" alt=""> </div> <div id="actGotop" class="actGotop"> <a href="javascript:0"></a> </div> </body> <style> a { color: #FFF; }
.actGotop { position: fixed; bottom: 50px; right: 100px; width: 150px; height: 195px; display: none; z-index: 100; }
.actGotop a, .actGotop a:link { width: 200px; height: 195px; display: inline-block; background: url(btop.png) no-repeat; outline: none; }
.actGotop a:hover { width: 200px; height: 195px; background: url(btop1.png) no-repeat; outline: none; } </style> 接下来我们来看一下如何用jQuery实现最终效果。 script src="jquery-1.12.4.js"></script> <script> $(function(){ $(window).scroll(function(){ if ($(window).scrollTop()>=1000) { $(".actGotop").stop().fadeIn(300); } else { $(".actGotop").stop().fadeOut(300); } }) $(".actGotop").click(function(){ $("body,html").stop().animate({scrollTop:0},400); })
}) </script> 实现过程分析: 首先判断滚动距离,超过1000时返回顶部图标会以fadeIn的动画显示出来,小于1000则隐藏。 点击返回顶部图标后注意,不能写成$(window).animate()要写$("body,html")才可以。想让动画效果慢一些可以把animate里后面的400参数修改大一些。 另外一定记得给fadeIn、fadeOut和animate前面加stop()方法,否则会在连续快速触发动画的时候出现bug。 以上就是小猿圈web前端讲师给大家分享的教你用jQuery做个返回顶部按钮,希望对小伙伴们有所帮助web前端自学②群:738735873,想要了解更多内容的小伙伴可以登录小猿圈官网了解。
|