js实现返回顶部功能
1、css
<style>
body {
height: 2000px;
background-color: aqua;
}
#imgObj {
position: fixed;
bottom: 50px;
right: 50px;
display: none;
}
</style>
2、html样式
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
</ul>
<img src="./images/tianshi.gif" alt="" id="imgObj">
</body>
3、js部分
<script>
var img = document.getElementById('imgObj')
window.onscroll = function () {
var scrollTop = document.documentElement.scrollTop
var clientHeight = document.documentElement.clientHeight
if (scrollTop >= clientHeight) {
img.style.display = 'block';
} else {
img.style.display = 'none';
}
img.onclick = function () {
var timer = setInterval(function () {
document.documentElement.scrollTop -= 5;
console.log(scrollTop);
if (scrollTop = 0) {
clearInterval(timer)
}
}, 10)
}
}
</script>