我为我的简单滑块写了一些代码,但有些东西出错了
我想重置canvasHeight
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
img.css({'top':- (height -canvasHeight) })
canvasHeight+=100
var top = img.css('top')
if (top == '0px'){
myStopFunction()
img.css({'top':-height})
canvasHeight = 0
canvasHeight+=100
height = new $('img').height() - canvasHeight;
setInterval(function(){ myTimer() }, 1000);
}
}
function myStopFunction() {
clearInterval(myVar);
}
答案 0 :(得分:0)
您没有将重新启动它的setInterval
分配给myVar
变量,因此下次您尝试清除它时,它仍然使用原始呼叫中的间隔ID。这会导致多个时间间隔正在运行,因此会对您的函数进行多次竞争调用。
另外,你有一堆隐式的全局变量,因为你错过了逗号分隔符。
var img = $('img'),
time = 2000,
top = img.css('top'),
canvasHeight = 100,
height = $('img').height() - canvasHeight;
img.css({
'top': -height
})
var myVar = setInterval(myTimer, 1000);
function myTimer() {
img.css({ 'top': -(height - canvasHeight) })
canvasHeight += 100
var top = img.css('top')
if (top == '0px') {
myStopFunction()
img.css({ 'top': -height })
canvasHeight = 0
canvasHeight += 100
height = new $('img').height() - canvasHeight;
myVar = setInterval(myTimer, 1000);
}
}
function myStopFunction() {
clearInterval(myVar);
}
.box {
position: relative;
width: 320px;
height: 100px;
margin: 0 auto;
overflow: hidden;
}
.scene {
height: 100%;
width: 100%;
float: left;
background-color: #996711;
}
.scene-element {
position: relative;
left: 0;
width: 100%;
height: 100%;
}
.scene-element img {
position: absolute;
-webkit-transition: all ease .8s;
-moz-transition: all ease .8s;
-o-transition: all ease .8s;
transition: all ease .8s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="scene">
<div class="scene-element">
<img src="https://image.ibb.co/gXKiMR/01.png">
</div>
</div>
</div>
我还删除了您传递给setInterval
的匿名函数。如果没有其他代码可以运行,你可以传递你正在调用的实际函数。