13618602336

原生js回到顶部代码

2015-01-09 09:31 浏览 次 来源:未知

经常看到回到顶部的效果,最简单的就是直接一个a标签,点击瞬间跳转到顶部,不过我们可以做的用户体验更好一点,就是当页面滚动到一定距离时才显示“回到顶部”图标,点击图标时有个滚动的效果,这样感觉会更好点,要实现这样的效果,jquery很简单,在这里就不介绍了,但是如果只想要这一个效果,用jquery未免大材小用了,今天写了个原生js的代码,分享出来看;

html:只要id=“gotop”就行,其它的你随便写

<a href="#" rel="nofollow" id="gotop">↑</a>

css:这里是用样式当标签定位到页面的右下角

<style type="text/css">
body,html{_background: url(alout:blank);}
a{text-decoration: none;text-align: center;color: #fff;font-size: 30px;font-weight: bold;}
.wrap{width: 500px;margin: 0 auto;}
    #gotop{width:50px;height:50px;line-height: 50px; background: #f00;position: fixed;right: 20px;bottom:20px;display: none;_position: absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,20)||0)-(parseInt(this.currentStyle.marginBottom,20)||0)));}
</style>

js:

<script type="text/javascript">
   function myScroll(){
    var gotop=document.getElementById('gotop'),x=0,Fun=function(){
        x=document.documentElement && document.documentElement.scrollTop||document.body&&document.body.scrollTop;
        gotop.style.display=x>300?'block':'none';
    };
    window.setInterval(Fun,1);
    gotop.onclick=function(){
        var timer=setInterval(function(){
            x=Math.floor(.7*x);
            x<1&&clearInterval(timer);
             window.scrollTo(x,x);
         },1);
         return false;
    }
}
    myScroll();
</script>

武汉网站建设领导品牌!武汉网站建设首选珞珈学子网络科技,精英技术团队,技术咨询电话:027-68772750  13618602336

 

联系我们

CONTACT US

袁经理: 电话:027-68772750 地址:武汉市洪山区武珞路珞珈山大厦A座1701室 鄂ICP备09016823号-7