首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解jQuery事件背后的逻辑

问理解jQuery事件背后的逻辑
EN

Stack Overflow用户
提问于 2017-05-02 17:43:08
回答 1查看 69关注 0票数 0

我在StackOverFlow中找不到任何这样的问题(请原谅我错过了任何问题!)

下面的代码把我搞砸了。请注意,这是恢复/暂停动画。

代码语言:javascript
复制
$(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更新将如何工作?每次浏览器重新读取整个函数时,它都会被重写。

请帮帮我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-02 17:57:06

如果我正确理解它,您是在“运行”和“暂停”之间切换,作为动画播放状态属性的值吗?

见下文。

​

代码语言:javascript
复制
$(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");
    }
  })
});
代码语言:javascript
复制
.slider {
animation-play-state: running; 
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider"> hallo </div>

​

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43744107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档