1、在html里面写上锚链接和top按钮和并调整好位置和样式:
2、在页面的script标签内添加以下代码即可:
//获取滚动条的位置
function getScrollTop() {
var scrollPos;
if (window.pageYOffset) {
scrollPos = window.pageYOffset;
} else if (document.compatMode && document.compatMode != 'BackCompat') {
scrollPos = document.documentElement.scrollTop;
} else if (document.body) {
scrollPos = document.body.scrollTop;
}
return scrollPos;
}
//监听滚动条
var totop = document.querySelector(".top")
window.onscroll = function() {
if (getScrollTop() > 500) {
totop.style.display = "block"
} else {
totop.style.display = "none"
}
}