我有两个矩形,一个蓝色,一个绿色(绿色被overflow隐藏)。我正在尝试使绿色矩形向上移动,直到它到达蓝色矩形的顶部时,一个按钮被单击。我是Javascript的新手,不知道哪里错了。javascript背后的思想过程是,我获取元素,如果它的位置位于容器的顶部,则停止函数,否则从底部递增它,以便它向上移动。
我的代码如下所示:
CSS
body {
margin: 0;
padding: 0;
text-align: center;
}
#container{
position: relative;
background-color: brown;
height: 800px;
width: 800px;
margin: 0 auto;
margin-top: 75px;
}
#fullLoad{
position: relative;
height: 600px;
width: 200px;
background: blue;
left: 300px;
top: 100px;
overflow: hidden;
border-radius: 20px 20px 20px 20px;
}
#loader{
border-radius: 20px 20px 20px 20px;
z-index: 2;
position: absolute;
height: 600px;
width: 200px;
background: green;
top: 600px;
}
#btn{
position: absolute;
top: 20px;
right: 362px;
padding: 5px 20px;
border-radius: 10px;
background: gold;
font-family: sans-serif;
font-size: 1.8em;
color: #424242;
}
HTML
<div id="container">
<div id="fullLoad">
<div id="loader"></div>
</div>
<input id="btn" type="button" value="Go !" onclick="load()">
</div>
Javascript
function load() {
var loader = document.getElementById("loader");
var pos = 600;
var id = setInterval(frame, 5);
function frame() {
if (pos == 0) {
clearInterval(id);
} else {
pos++;
loader.style.bottom = pos + 'px';
}
}
}
发布于 2018-09-15 05:55:20
你只需要改变
pos++;
loader.style.bottom = pos + 'px';
至
pos--;
loader.style.top = pos + 'px';
因为你是从顶部的600px开始的,你想要达到0。
证明:
function load() {
var loader = document.getElementById("loader");
var pos = 600;
var id = setInterval(frame, 5);
function frame() {
if (pos == 0) {
clearInterval(id);
} else {
pos--;
loader.style.top = pos + 'px';
}
}
}
body {
margin: 0;
padding: 0;
text-align: center;
}
#container{
position: relative;
background-color: brown;
height: 800px;
width: 800px;
margin: 0 auto;
margin-top: 75px;
}
#fullLoad{
position: relative;
height: 600px;
width: 200px;
background: blue;
left: 300px;
top: 100px;
overflow: hidden;
border-radius: 20px 20px 20px 20px;
}
#loader{
border-radius: 20px 20px 20px 20px;
z-index: 2;
position: absolute;
height: 600px;
width: 200px;
background: green;
top: 600px;
}
#btn{
position: absolute;
top: 20px;
right: 362px;
padding: 5px 20px;
border-radius: 10px;
background: gold;
font-family: sans-serif;
font-size: 1.8em;
color: #424242;
}
<div id="container">
<div id="fullLoad">
<div id="loader"></div>
</div>
<input id="btn" type="button" value="Go !" onclick="load()">
</div>
https://stackoverflow.com/questions/52338194
复制相似问题