如何移除预先准备好的容器

How to remove a container prepended to the body

本文关键字:准备好 何移      更新时间:2023-11-01

我已经创建了一个容器,并将其准备到正文中:

// Create container
var container = "<div class='foo'> ... </div>";
// Prepend it to the body
$("body").prepend(container);

现在我想在几秒钟后淡出容器:

setTimeout(function() {
    container.fadeOut();
}, 3000);

然而,它说undefined不是一个函数。我很确定$(".foo").fadeOut()会起作用,但我有很多.foo容器,我不想为每个容器分配单独的id。

使container var指向jq对象而不是字符串:

var container = $('<div class="foo"> ... </div>');
// Prepend it to the body
$("body").prepend(container);
setTimeout(function() {
   container.fadeOut();
}, 3000);

现在,container有一个fadeOut()方法,而不是一个哑字符串。

编辑:根据请求,创建部分的香草版本:

var container = document.createElement("div");
container.className="foo";
container.innerHTML= "<b>Hello world</b>";
document.body.insertBefore(container, document.body.firstChild);

香草中的fadeOut部分:

<style> 
        div.foo{ opacity: 1; transition: 1000ms opacity;}
        div.foo.fade { opacity: 0; }
</style>
  setTimeout(function(){ container.classList.add("fade");}, 3000);

应该是这样的:

var container = $("<div class=`foo`><h1>Hello World</h1></div>")
$("body").prepend(container);
setTimeout(function() {
    container.fadeOut();
}, 3000);

此处的工作代码

这样尝试:

$(document).ready(function(){
   var container = $("<div class='foo'><h1>Something...</h1></div>")
   $("body").prepend(container);
   setTimeout(function() {
   container.fadeOut();
   }, 3000);
});

您正在将一个字符串传递给您的'container'变量。fadeOut功能仅适用于DOM对象。不是字符串。使用将字符串转换为DOM对象

var container = $('Your Code Here');

container是字符串变量。容器字符串表示的DOM元素可以像$('div.foo')一样访问。所以你的fadeout呼叫会像->一样改变

setTimeout(function() {
    $('div.foo').fadeOut();
}, 3000);