jQuery之scroll用法例項
阿新 • • 發佈:2018-11-11
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 *{ 8 margin:0; 9 padding: 0; 10 } 11 .div1,.div2{ 12 width: 100%; 13 height: 800px;14 15 } 16 .div1{ 17 /*border: 5px solid red;*/ 18 /*padding: 20px;*/ 19 /*margin: 2px;*/ 20 background-color:antiquewhite; 21 } 22 .div2{ 23 background-color:rebeccapurple; 24 } 25 .returntop{ 26 position: fixed;27 right: 20px; 28 bottom: 20px; 29 width: 80px; 30 height: 50px; 31 background-color:yellow; 32 text-align: center; 33 line-height: 50px; 34 } 35 .hide{ 36 display: none; 37 } 38 </style> 39</head> 40 <body> 41 <div class="div1"></div> 42 <div class="div2"></div> 43 <div class="returntop hide" onclick="returntop()">返回頂部</div> 44 <script src="jquery-3.3.1.min.js"></script> 45 <script> 46 // 相對於檢視視窗 47 // console.log($('.div1').offset().top); 48 // console.log($('.div1').offset().left); 49 // 50 // console.log($('.div2').offset().top); 51 // console.log($('.div2').offset().left) 52 53 // console.log($('.div1').position().top); 54 // console.log($('.div1').position().left); 55 56 // console.log($('.div2').position().top); 57 // console.log($('.div2').position().left) 58 window.onscroll=function () { 59 // console.log($(window).scrollTop()) 60 if($(window).scrollTop()>50){ 61 $('.returntop').removeClass('hide') 62 } 63 else { 64 $('.returntop').addClass('hide') 65 } 66 } 67 function returntop() { 68 $(window).scrollTop(0); 69 } 70 </script> 71 </body> 72 </html>