js和jquery实现回到顶层

来源:互联网 发布:java包装类 编辑:程序博客网 时间:2024/05/16 04:55

js

<!DOCTYPE html><html><head><title>返回顶部</title><style>body{margin:0; padding:0}#to_top{width:30px; height:40px; padding:20px; font:14px/20px arial; text-align:center;  background:#06c; position:absolute; cursor:pointer; color:#fff}</style><script>window.onload = function(){  var oTop = document.getElementById("to_top");  var screenw = document.documentElement.clientWidth || document.body.clientWidth;  var screenh = document.documentElement.clientHeight || document.body.clientHeight;  oTop.style.left = screenw - oTop.offsetWidth +"px";  oTop.style.top = screenh - oTop.offsetHeight + "px";  window.onscroll = function(){    var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;    oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px";  }  oTop.onclick = function(){    document.documentElement.scrollTop = document.body.scrollTop =0;  }}  </script></head><body style="height:1000px;"><h1>返回顶部</h1><div id="to_top">返回顶部</div></body></html>


要点一:document.documentElement.clientWidth || document.body.clientWidth; 获得可视区的宽度。后面是兼容chrome,前面是兼容其它浏览器。

要点二:oTop.style.left = screenw - oTop.offsetWidth +"px";  当页面加载时,让元素的位置位于页面最右边,用可视区的宽度减去元素本身的宽度。

要点三:oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; 当页面滚动时,元素的Y坐标位置等于可视区的高度减去元素本身的高度,加上滚动距离。

要点四:document.documentElement.scrollTop = document.body.scrollTop =0; 当点击元素时,让页面的滚动距离为0.写两个是为了兼容。



jquery

<html><script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.7.2.min.js"></script><script> $(function(){         //当滚动条的位置处于距顶部100像素以下时,跳转链接出现,否则消失        $(function () {             $(window).scroll(function(){                 if ($(window).scrollTop()>100){                     $("#back-to-top").fadeIn(1500);                 }                 else                 {                     $("#back-to-top").fadeOut(1500);                 }             });            //当点击跳转链接后,回到页面顶部位置            $("#back-to-top").click(function(){                 $('body,html').animate({scrollTop:0},1000);                 return false;             });         });     }); </script><body><p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p><p>11</p><p>12</p><p>13</p><p>14</p><p>15</p><p>16</p><p>17</p><p>18</p><p></p><p id="back-to-top"><a href="#top"><span></span>返回顶部</a></p></body></html>


0 0
原创粉丝点击