我可以添加叠加层,但是我无法删除它(jQuery) [英] I can add an overlay, but I can't remove it (jQuery)
问题描述
此功能为整个浏览器屏幕添加一个覆盖图,其中包含以下属性:
$('a.cell') .click(function(){
$('< div id =overlay/>').appendTo('body').fadeIn(\"slow);
});
#overlay
{
background-color:black;
宽度:100%;
身高:100%;
位置:固定;
top:0;
剩下:0;
display:none;
z-index:100;
不透明度:0.5;
}
这个函数应该删除它。
$('#overlay')。click(function(){
$(this).fadeOut(slow)。remove() ;
});
但它看起来完全没有任何功能,现在我的页面被一个黑色卡住了。删除有什么问题?
问题在于,当您添加时, code>处理程序,没有任何重叠,所以您将处理程序添加到一组空元素。
要解决此问题,请使用< a href =http://docs.jquery.com/Events/live#typefn =nofollow noreferrer> live 方法将你的处理程序绑定到匹配 #overlay的所有元素
另外, fadeOut
不是阻塞呼叫,所以它在元素完成淡出之前返回。因此,在元素开始淡出之后立即调用 remove
。
要解决此问题,请在动画完成后使用 fadeOut
的回调参数调用 remove
。
例如:
$('#overlay')。live(function(){
$(this).fadeOut(slow,function(){$(this).remove();});
});
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.
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(); });
});
这篇关于我可以添加叠加层,但是我无法删除它(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!