今晚,我自己寫了一個很簡單的回到的頂部的js,同時也希望自己能在原生JS上面有發展,與大家共勉!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript backToTop</title>
</head>
<body>
<div style="width:100%;height:1000px;"></div>
<script type="text/javascript">
;(function(){
var container = document.createElement('div'),
body = document.getElementsByTagName('body')[0],
doc = document.body,
style = [
"border: 1px solid #ccc;",
"position: fixed;",
"width: 40px;",
"height: 40px;",
"bottom: 100px;",
"left: 50%;",
"margin-left: 500px;",
"z-index: 9999;",
"cursor: pointer;",
"display: none;"
].join(""),
icon = document.createElement('div'),
iconStyle = [
"width: 10px;",
"height: 10px;",
"position: absolute;",
"border-top: 2px solid #ccc;",
"border-left: 2px solid #ccc;",
"top: 18px;",
"left: 15px;",
"transform: rotate(45deg);",
"-webkit-transform: rotate(45deg);",
"-moz-transform: rotate(45deg);",
"-o-transform: rotate(45deg);"
].join("");
container.style.cssText = style;
icon.style.cssText = iconStyle;
container.appendChild(icon);
body.appendChild(container);
window.addEventListener('scroll',function(){
var scrollTop = doc.scrollTop;
console.log(scrollTop);
if(scrollTop > 200) {
container.style.display = "block";
} else {
container.style.display = "none";
}
},false);
container.addEventListener('click',function(){
setTimeout(function() {
document.body.scrollTop = 0;
},0);
},false);
})();
</script>
</body>
</html>