1 var $this = $('.container-scroll'), 2 $goup = $('.goup'), 3 //元素可视区的高度 4 offtop = $(window).height() - $this.offset().top, 5 isscroll =false; 6 //监听滚动事件 控制 回到顶部按钮出现 7 $this.on('scroll',function () { 8 var rolltop = $this.scrollTop(); 9 if ( rolltop > offtop) { 10 $goup.css({'opacity':.5,'bottom':40+'px'}); 11 }else if(rolltop < offtop){ 12 $goup.css({'opacity':.5,'bottom':-40+'px'}); 13 } 14 }); 15 16 $goup.on('click',function () { 17 isscroll =true; 18 gotop(); 19 }); 20 21 $this.on('touchstart',function () { 22 isscroll = false; 23 }); 24 25 26 function gotop(){ 27 var y = Math.max(0,$this.scrollTop()); 28 var speed = 1.2; 29 $this.scrollTop( Math.floor(y / speed)); 30 if (isscroll && $this.scrollTop() > 0) { 31 var timer= setTimeout(gotop, 10); 32 }else if(!isscroll){ 33 clearTimeout(timer); 34 } 35 }