jquery监听滚动条,实现“返回顶部”

来源:互联网 发布:淘宝48分店铺解封 编辑:程序博客网 时间:2024/05/17 07:37

我们在浏览网页时,网页内容过多会使得滚动条缩小并越来越靠近页面底部,当想返回到页面最顶端时靠滚动鼠标会很麻烦,因此在很多网页在靠近滚动条处都有一个“返回顶部”等内容的按钮,以快速的回到页面最顶端。接下来我们详细描述如何实现这一功能

1、html

<!--显示右侧快速导航栏-->    <div class="quick_bar" id="quick_bar">        <a id="to_top" class="to_top" title="返回顶部"  href="javascript:void(0)">            <img src="{$Think.const.IMG_URL}top.png" alt="返回顶部"/>        </a>        <a id="to_reply" class="to_reply" title="快速留言" href="javascript:void(0)" >            <img src="{$Think.const.IMG_URL}reply.png" alt="快速留言"/>        </a>    </div>
2、css样式

.quick_bar {position: fixed;left: 95%; top:40%;width: 50px;height: 150px;}.to_top { display: none}.to_top:hover{ opacity:0.5}.to_reply {display: block}.to_reply:hover{ opacity: 0.5}


3、监听滚动条与页面顶部的距离

$(document).scroll(function(){            var top=$(document).scrollTop();            if(top<300){                $('#to_top').hide();            }            else{                $('#to_top').show();            }        })

其中“to_top”是“返回顶部”按钮的ID,

$(document).scroll(function(){}是滚动条移动时触发的事件
$(document).scrollTop()是监测滚动条距离页面顶部的距离
if判断条件中,当滚动条距离页面小于300px时,则不显示“返回顶部”,否则显示
4、事件响应
<pre name="code" class="javascript">$('#to_top').click(function(){            $('body,html').animate({scrollTop:0},300);        })
返回页面顶部,时间设置为300毫秒

页面效果为:


0 0
原创粉丝点击