I can add an overlay, but I can't remove it (j

2019-07-24 18:52发布

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?

5条回答
姐就是有狂的资本
2楼-- · 2019-07-24 19:11

Try:

$('#overlay').live('click', function()  {
        $(this).fadeOut("slow").remove();
});
查看更多
Emotional °昔
3楼-- · 2019-07-24 19:27

My recommendation is to use the jquery.tools overlay plugin. Your overlay will have a trigger (usually a button or link), but you can load or clear it with a javascript command, e.g.:

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:

<div id="myOverlay" style="display:none;">Be sure to set width and height css.</div>
<button id="myTrigger" rel="#myOverlay">show overlay</button>
查看更多
啃猪蹄的小仙女
4楼-- · 2019-07-24 19:29

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.

To fix this, use the live method to bind your handler to all elements that match #overlay, whenever they are created.

Also, fadeOut is not a blocking call, so it returns before the element finishes fading out. Therefore, you're calling remove right after the element starts fading out.

To fix this, use fadeOut's callback parameter to call remove after the animation finishes.

For example:

$('#overlay').live(function() { 
    $(this).fadeOut("slow", function() { $(this).remove(); });
});
查看更多
我想做一个坏孩纸
5楼-- · 2019-07-24 19:36

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() });
});
查看更多
Juvenile、少年°
6楼-- · 2019-07-24 19:36

Remove should be in the callback to fadeout, like so:

$('#overlay').live('click', function()  {
    $(this).fadeOut("slow", function() {
       $(this).remove();
    });
});
查看更多
登录 后发表回答