繁体   English   中英

切换什么触发jQuery中的事件而无需重新加载?

[英]Switch what triggers an event in jQuery without reloading?

因此,我有一个网站,该网站加载开始时已暂停的GIF。 我有.on(“ event”)函数,它们分别在单击和悬停时可以正常工作。 但是,我想让用户选择他们要使用哪种方法通过设置播放gif。 我正在使用的代码是这样的:

if (hoverOn) {
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
   $(document).on("click", ".content", function () {
       playTheGif();

当然,单击时它会暂停gif(如果已在播放)。

我有用于设置bool hoverOn的按钮,该按钮可以更改bool,但不会重新加载页面,因此即使bool发生变化,播放gif的触发器也保持不变。 有什么方法可以使if / else搜索在页面中动态化?

谢谢,我希望自己能解释清楚。

切换布尔测试和处理程序的位置,以便在处理程序内部测试布尔值:

$(document).on("hover", ".content", function () {
  if (hoverOn) playTheGif();
})
$(document).on("click", ".content", function () {
  if (!hoverOn) playTheGif();
});

我可能会尝试将它们结合起来。

$(document).on("click mouseenter", ".content", function (e) {
    //do nothing for hoveron,click or hoveroff,hover
    if (hoverOn ^ e.type === "mouseenter") return;

    playTheGif();
});

 var hoverOn = true; $(document.body).on("click mouseenter", ".content", function (e) { //do nothing for hoveron,click or hoveroff,hover if (hoverOn ^ e.type === "mouseenter") return; //playTheGif(); $(e.target).css('backgroundColor', 'green'); }); $('button').on('click', function(){ hoverOn = !hoverOn; $('#interaction').text(hoverOn ? 'hover' : 'click' ); $('.content').css('backgroundColor', ''); }); 
 .content { display: inline-block; width: 150px; height: 150px; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div> <button>Toggle Interaction</button> <span id="interaction">hover</span> </div> 

当用户切换hoverOn时,可以取消设置当前事件并设置新事件。 例如:

if (hoverOn) {
    $(".content").unbind("click");
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
    $(".content").unbind("hover");
    $(document).on("click", ".content", function () {
        playTheGif();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM