结合setTimeout和clearTimeout,当页面停止滚动时,“返回顶部”按钮淡隐淡出。点击“返回顶部”页面以动画形式返回顶部。完美兼容ie6-11,firefox,chrome等。
html代码如下:
<a href="javascript:void(0)" id="backToTop" class="backToTop">ToTop</a>
css代码如下:
html {_background: url(about: blank);}/* 解决在ie6下颤抖的问题 */ .backToTop {width: 80px; height: 80px; line-height: 80px; display: none; background: #d1d1d1; position: fixed; bottom: 20px; top: auto; right: 20px; z-index: 1200; text-align: center; cursor: pointer;} *html .backToTop {position: absolute; bottom: auto; top: expression(eval(document.documentElement.clientHeight + document.documentElement.scrollTop - this.offsetHeight - 20))} .backToTop:hover {background: #ccc; text-decoration: none;}
js代码如下:
backToTop($(‘#backToTop‘)); function backToTop(dom) { var $backToTop = dom; var start = null, backT = null; backT = function() { clearTimeout(start); start = setTimeout(function() { //结合setTimeout和clearTimeout,当页面停止滚动时,返回顶部按钮淡隐淡出 if($(window).scrollTop() > 300) { $backToTop.fadeIn(400); } else { $backToTop.fadeOut(400); } }, 400); } backT(); $(window).scroll(function() { backT(); }); $(window).resize(function() { backT(); }); $backToTop.on("click", function() { $("html, body").animate({ scrollTop: "0px" }, 200); $backToTop.fadeOut(400); return false; }); }
时间: 2024-11-10 03:01:23