如何让JavaScript动画滚动到元素的底部并返回顶部?我还在学习JavaScript,并从w3schools找到了一个示例代码,当我修改它以滚动回到顶部时,在Tryit编辑器中工作,使用与我在下面的myUP函数完全相同的代码。虽然我知道在当前状态下,结合其他功能,这个相同的代码目前还没有工作。
我预感到代码有些不太好,即使它在Tryit编辑器中单独工作也是如此。我觉得将来它不会正常工作。我是否正确地承担这一点,如果是这样,我应该怎样做才能在JavaScript中实现这一目标呢?
<html>
<style>
#myContainer {
width: 500px;
height: 500px;
position: relative;
background: black;
}
#tester {
width: 500px;
height: 50px;
position: absolute;
background-color: gray;
}
</style>
<body>
<p>
<button onmousedown="myMove()">DOWN</button>
</p>
<p>
<button onmousedown="myUP()">UP</button>
</p>
<div id ="myContainer">
<div id ="tester"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
function myUP() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.bottom = pos + 'px';
}
}
}
</script>
</body>
答案 0 :(得分:0)
立即检查工作代码,
您的代码在UP
函数中出现问题。
function myUP() {
var elem = document.getElementById("tester");
var pos = 500;// Changed the max position.
var id = setInterval(frame, 20);
function frame() {
console.log(pos);
if (pos == 0) { //reverse condition to 0
clearInterval(id);
} else {
pos--; // reverse the position
elem.style.top = pos + 'px'; // that should be back to top
}
}
}
<html>
<style>
#myContainer {
width: 500px;
height: 500px;
position: relative;
background: black;
}
#tester {
width: 500px;
height: 50px;
position: absolute;
background-color: gray;
}
</style>
<body>
<p>
<button onmousedown="myMove()">DOWN</button>
</p>
<p>
<button onmousedown="myUP()">UP</button>
</p>
<div id ="myContainer">
<div id ="tester"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("tester");
var pos = 0;
var id = setInterval(frame, 20);
function frame() {
if (pos == 500) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
function myUP() {
var elem = document.getElementById("tester");
var pos = 500;
var id = setInterval(frame, 5);
function frame() {
console.log(pos);
if (pos == 0) {
clearInterval(id);
} else {
pos--;
elem.style.top = pos + 'px';
}
}
}
</script>
</body>
&#13;