简体   繁体   English

单击时,Fancybox不会关闭

[英]Fancybox won't close when click spans

I want the fancybox to close when either of the spans are clicked, currently it seems to be reopening the window after they are clicked and clicking anywhere else closes it like it should. 我希望在单击两个跨度中的任何一个时都关闭fancybox,当前似乎在单击它们之后正在重新打开窗口,然后单击其他任何位置都将其关闭。

<div class="fancybox" style="display: none;">
    <span class="ChooseEnglish">English</span>
    <span class="ChooseCymraeg">Cymraeg</span>
</div>    

$(".fancybox").fancybox({
    closeClick: true
});
$( ".fancybox" ).trigger( "click" );

$( ".ChooseEnglish" ).click(function() {
    $.fancybox.close();
});
$( ".ChooseCymraeg" ).click(function() {
    $.fancybox.close();
});

http://jsfiddle.net/K8NDm/ http://jsfiddle.net/K8NDm/

Thanks 谢谢

Alex 亚历克斯

The issue is that the selector .fancybox is bound to fancybox but it's also the content of fancybox. 问题是选择器.fancybox绑定到了fancybox, 但这也是fancybox的内容 In other words, that selector is both the trigger and the target of fancybox. 换句话说,该选择器既是fancybox的触发器 ,也是其目标

Of course, any click on the selector and/or its contents (your <span> ) will trigger fancybox over an over again. 当然, click选择器和/或其内容(您的<span> )将再次触发fancybox。

You need another selector to fire fancybox (that can be hidden if you prefer so) like : 您需要另一个选择器来启动fancybox(如果愿意,可以将其隐藏),例如:

<a href="#fancybox" class="fancybox" style="display: none;"><a>

Then change the div selector from class to ID so it can be targeted by the link like : 然后将div选择器从更改为ID,以便可以通过以下链接进行定位:

<div id="fancybox" style="display: none;">
    <span class="ChooseEnglish">English</span>
    <span class="ChooseCymraeg">Cymraeg</span>
</div> 

and finally the simplified script : 最后是简化的脚本:

$(".fancybox").fancybox({
    closeClick: true
}).trigger("click"); // you can chain fancybox and trigger methods

$(".ChooseEnglish, .ChooseCymraeg").click(function () {
    $.fancybox.close();
}); // bind the same click event to both selectors at once

See JSFIDDLE 参见JSFIDDLE


NOTE : if you want to prevent the visitor from closing fancybox without choosing any of your ( <span> ) options, then you can add modal:true instead like : 注意 :如果要防止访问者在选择任何( <span> )选项的情况下关闭fancybox,则可以添加modal:true而不是:

$(".fancybox").fancybox({
    // force to close clicking on any span only
    modal: true
}).trigger("click");

See forked JSFIDDLE 参见分叉的JSFIDDLE

The click event is bubbling from the span to the div, so the fancybox gets reopened. click事件正在从范围到div冒泡,因此重新打开了花式框。 You can use .stopPropagation to prevent bubbling: 您可以使用.stopPropagation防止冒泡:

$( ".ChooseEnglish" ).click(function(e) {
    e.stopPropagation();
    $.fancybox.close();
});
$( ".ChooseCymraeg" ).click(function(e) {
    e.stopPropagation();
    $.fancybox.close();
});

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

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