jQuery 返回顶部 效果

用jQuery实现简单的页面滑动到某个位置后, 出现'回到顶部'按钮, 点击后返回顶部的效果.
html代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.top-btn{
            z-index: 999;
            display: none;
            position: fixed;
            right: 0;
            bottom: 3rem;
            width: 1rem;
            height: 1rem;
            background-color:blueviolet;
        }
	</style>
</head>
<body>
	<div class="top-btn"></div>
</body>
</html>

Javascript代码

//获取屏幕高度,滚动后显示回到顶部图标
            var height = window.screen.height;
            $(window).scroll(function () {
                //获取滚动条到顶部的垂直高度
                var top = jQuery(document).scrollTop();
                //到一定高度显示
                if (top > height+100) {
                    jQuery(".top-btn").fadeIn(300);
                }
                //小于一定高度的时候消失
                if (top < height+100) {
                    jQuery(".top-btn").fadeOut(200);
                }
            });
            //点击回到顶部
            $('.top-btn').click(function () {
                jQuery('html, body').animate({
                    scrollTop: 0
                }, 500);
            });
posted @ 2018-01-15 17:22  DarthBadwolf  阅读(122)  评论(0编辑  收藏  举报