<a href="#" class="top">顶部</a>然后设置其样式表:
body {height: 3000px;}.top {position: absolute;top: 120px;display: inline-block;width: 50px;height: 50px;line-height: 50px;text-decoration: none;text-align: center;background-color: #666666;color: #ffffff;right: 10px;transition: all 0.3s; visibility: hidden;}.top:hover {background-color: #ff3300;}这里body设定为3000的高度, 主要是让页面有滚动的效果. 按钮一般都是放在网页的右边靠下一点的位置. 这里我们通过position来设置.window.onscroll = function (e) {...}在这个事件里我们来控制返回顶部按钮的上下位置, 和是否显示. 首先来完成上下位置的控制.var n_half_height = window.screen.height / 2;将这个值赋给按钮的top属性.
var n_stop = e.target.scrollingElement.scrollTop; //获取scrollTop的高度var n_top = n_stop + n_half_height;//得到位置这是e 对象是onsroll里的参数event. 这里我使用的是谷歌浏览器.其他浏览器未测试. 如果需要兼容, 大家可以处理一下.
var ele_body = document.body;var ele_top = document.getElementsByClassName("top")[0];var n_half_height = window.screen.height / 2;ele_top.style.top = n_half_height + "px";window.onscroll = function (e) { var n_stop = e.target.scrollingElement.scrollTop; if (n_stop === 0 ) {ele_top.style.visibility = "hidden"; }else {ele_top.style.visibility = "visible"; } var n_top = n_stop + n_half_height ; ele_top.style.top = n_top + "px";}最后的效果展示:
以上就是本文的全部内容,希望对大家的学习有所帮助。