js简单的点击返回顶部效果实现方法
来源:易贤网 阅读:567 次 日期:2016-06-30 09:25:28
温馨提示:易贤网小编为您整理了“js简单的点击返回顶部效果实现方法”,方便广大网友查阅!

当页面特别长的时候,用户想回到页面顶部,必须得滚动好几次滚动键才能回到顶部,如果在页面右下角有个“返回顶部”的按钮,用户点击一下,就可以回到顶部,对于用户来说,是一个比较好的体验。

实现原理:当页面加载的时候,把元素定位到页面的右下角,当页面滚动时,元素一直位于右下角,当用户点击的时候,页面回到顶部。

要点一: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.写两个是为了兼容。

上代码:

<!doctype html>

<html>

<head>

<meta charset=utf-8 />

<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>

更多信息请查看脚本栏目
由于各方面情况的不断调整与变化,易贤网提供的所有考试信息和咨询回复仅供参考,敬请考生以权威部门公布的正式信息和咨询为准!
关于我们 | 联系我们 | 人才招聘 | 网站声明 | 网站帮助 | 非正式的简要咨询 | 简要咨询须知 | 加入群交流 | 手机站点 | 投诉建议
工业和信息化部备案号:滇ICP备2023014141号-1 云南省教育厅备案号:云教ICP备0901021 滇公网安备53010202001879号 人力资源服务许可证:(云)人服证字(2023)第0102001523号
云南网警备案专用图标
联系电话:0871-65317125(9:00—18:00) 获取招聘考试信息及咨询关注公众号:hfpxwx
咨询QQ:526150442(9:00—18:00)版权所有:易贤网
云南网警报警专用图标