回到顶部

来源:互联网 发布:佛教用品淘宝店 编辑:程序博客网 时间:2024/04/28 20:31

”回到顶部“在web中经常用到,一个简单写法。

script

<script>    window.onload = function(){    var oBtn = document.getElementById('btn');    var timer = null;    var bSys = true;    // 检测用户事件    window.onscroll = function(){    if(!bSys){    clearInterval(timer);    }    bSys = false;    }        oBtn.onclick = function(){        timer = setInterval(function(){    var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;    var iSpeed = Math.floor(-scrollTop/8);//向下取整        if(scrollTop == 0){    clearInterval(timer);    }    bSys = true;    document.documentElement.scrollTop = document.body.scrollTop = scrollTop + iSpeed;    },30);    };    };    </script>

jquery

// back to top;(function($){$.fn.btt = function(options){var defaults = {cScrollTop:200,   // 滚动条距离顶部高度cBtm:60,           // 回到顶部距离底部高度cDuration:500      // 会动顶部所用时间},opts = $.extend({},defaults, options);return this.each(function(){var _this= $(this);if(_this){_this.on('click',function(){$('html,body').animate({scrollTop: 0},opts.cDuration);});$(window).on('scroll',function(){var theScrollTop = $(document).scrollTop();opts.cScrollTop < theScrollTop ? _this.css('bottom', opts.cBtm +'px') : _this.css('bottom', -opts.cBtm + 'px');}).trigger('scroll');}});}})(jQuery);



html

<p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>    <p>空白</p>(可复制多些,效果明显)    <input type="button" id="btn" value="回到顶部"/>


css

<style>*{margin:0; padding: 0;}#btn{ position:fixed; right:20px; bottom:20px;}</style>



0 0
原创粉丝点击