嘿伙计们,当它移出屏幕时我需要停止它(500x500) 我不知道如何帮助?
<style>
#box { position: absolute; top: 0; left: 0; background-color: green; }
</style>
<script>
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
setInterval(animate,100);
}
</script>
</head>
<body>
<div id="box">The box</div>
</body>
答案 0 :(得分:1)
只需添加一项检查,看看下次移动是否会使该框达到或超过500.此外,我在框停止时添加了对clearInterval()
的呼叫,以停止计时器。 / p>
onload = function() {
var timer;
var theBox = document.getElementById("box");
function animate() {
if(theBox.offsetLeft+5 < 500 && theBox.offsetTop+5 < 500){
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
} else {
clearInterval(timer);
}
}
timer = setInterval(animate,100);
}
答案 1 :(得分:0)
我添加了if语句来检查页面的高度是否高于框顶部的偏移量:
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
if(window.innerHeight > (theBox.offsetTop+25)){
console.log(theBox.offsetTop+5)
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
}
setInterval(animate,100);
}