我在StackOverFlow中找不到任何这样的问题(请原谅我错过了任何问题!)
下面的代码把我搞砸了。请注意,这是恢复/暂停动画。
$(function() {
$('.slider').css("animation-play-state", "running");
var animVar = $('.slider').css("animation-play-state"); //animVar === "running" and on next click, it gets updated to "paused"
$('.slider').click(function() {
$(this).css("animation-play-state", function() {
if (animVar === "running") {
return "paused"; //returns "paused" to the function and the css property gets updated, overriding the one at the first line, changing the animVar on the next line.
} else {
return "running"; //returns "running" to the function and the css property gets updated, overriding the one at the first line, changing the animVar on the next line.
}
});
});
});问题是,如果我不更新if/else语句中的animVar,代码就无法工作。取而代之的是,一旦我点击它,它就会停下来,在连续的点击中,它就不会继续了。
但是,如果我确实在if / animVar语句(如animVar = "running"/"paused")中更新了animVar = "running"/"paused",它就可以正常工作。
我的问题是,首先我将动画播放状态设置为“运行”。
这将animVar设置为“运行”。
如果满足条件,动画就会像预期的那样“暂停”。
但这也应该覆盖顶部的$('.slider').css("animation-play-state", "running");,并将animVar重置为“暂停”,以便在下一次单击时,不满足if条件并执行out语句,从而在运行和单击暂停之间切换播放状态。
显然,我的逻辑出了问题。有人能让我明白吗?我的意思是,内部函数是闭包,所以它应该能够访问和更新外部函数的变量,对吗?
还有一件事。如果在每次单击时,浏览器从顶部读取它,因此每次将播放状态重置为“运行”,则If / each内部的animVar更新将如何工作?每次浏览器重新读取整个函数时,它都会被重写。
请帮帮我。
发布于 2017-05-02 17:57:06
如果我正确理解它,您是在“运行”和“暂停”之间切换,作为动画播放状态属性的值吗?
见下文。
$(function() {
$(".slider").click(function() {
var sliderClass = $(".slider").css("animation-play-state");
if(sliderClass == "running") {
$('.slider').css("animation-play-state", "paused");
console.log("running");
} else {
$(".slider").css("animation-play-state", "running");
console.log("paused");
}
})
});.slider {
animation-play-state: running;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider"> hallo </div>
https://stackoverflow.com/questions/43744107
复制相似问题