简体   繁体   English

我可以添加叠加层,但我无法删除它(jQuery)

[英]I can add an overlay, but I can't remove it (jQuery)

This function adds an overlay with the following properties to the entire browser screen, 此功能为整个浏览器屏幕添加具有以下属性的叠加层,

$('a.cell').click(function()    {
    $('<div id = "overlay" />').appendTo('body').fadeIn("slow");
});

#overlay
{
background-color: black;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: none;
z-index: 100;
opacity: 0.5;
}

And this function is supposed to remove it. 这个函数应该删除它。

$('#overlay').click(function()  {
    $(this).fadeOut("slow").remove();
});

But it seems to do absolutely nothing and now my page is stuck with a black overly over it. 但它似乎绝对没有任何东西,现在我的页面被黑色覆盖了过度。 What's wrong with the removal? 删除有什么问题?

The problem is that when you're adding the click handler, there isn't any overlay, so you're adding the handler to an empty set of elements. 问题是,当您添加click处理程序时,没有任何叠加,因此您将处理程序添加到一组空元素中。

To fix this, use the live method to bind your handler to all elements that match #overlay , whenever they are created. 要解决此问题,请使用live方法将处理程序绑定到匹配#overlay所有元素,无论何时创建它们。

Also, fadeOut is not a blocking call, so it returns before the element finishes fading out. 此外, fadeOut不是阻塞调用,因此它在元素完成淡出之前返回。 Therefore, you're calling remove right after the element starts fading out. 因此,您在元素开始淡出后立即调用remove

To fix this, use fadeOut 's callback parameter to call remove after the animation finishes. 要解决此问题,请在动画结束后使用fadeOut的callback参数调用remove

For example: 例如:

$('#overlay').live(function() { 
    $(this).fadeOut("slow", function() { $(this).remove(); });
});

Here you go. 干得好。 This should fix the problem and let the overlay fade out before removing it. 这应解决问题,并在删除之前让叠加淡出。

$('#overlay').live("click", function()  {
        $(this).fadeOut("slow", function() { $(this).remove() });
});

Remove should be in the callback to fadeout, like so: 删除应该在fadeout的回调中,如下所示:

$('#overlay').live('click', function()  {
    $(this).fadeOut("slow", function() {
       $(this).remove();
    });
});

Try: 尝试:

$('#overlay').live('click', function()  {
        $(this).fadeOut("slow").remove();
});

My recommendation is to use the jquery.tools overlay plugin . 我的建议是使用jquery.tools overlay插件 Your overlay will have a trigger (usually a button or link), but you can load or clear it with a javascript command, eg: 您的叠加层将有一个触发器(通常是按钮或链接),但您可以使用javascript命令加载或清除它,例如:

js: JS:

var config = { closeOnClick:true, mask:{opacity:0.7, color:'#333', loadSpeed:1} }
$("#myTrigger").overlay(config); // add overlay functionality
$("#myTrigger").data("overlay").load(); // make overlay appear
$("#myTrigger").data("overlay").close(); // make overlay disappear

html: HTML:

<div id="myOverlay" style="display:none;">Be sure to set width and height css.</div>
<button id="myTrigger" rel="#myOverlay">show overlay</button>

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

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