jquery - 为什么在 jquery 中添加第二个函数后我的对象没有出现?

标签 jquery html css delay

我在 jquery 中编写了一个简单的函数,它在单击按钮后将 css 类添加到带有照片的 div 中。
$('#btn1').click(function(){ $('#div1').addClass('show'});

我想要这个div(实际上是内容)弹出。 CSS:

#div1 {
display: none;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
max-width: 100%;
max-height: 100%;
margin: auto;
overflow: auto;
}

.show {
display: block!important;  
}

到目前为止效果很好。但我希望这个 div 在 2 秒后再次消失,所以我将其添加到 jquery 中:

$('#btn1').click(function(){
$('#div1').addClass('show').delay(2000).removeClass('show')
});

现在它根本不存在了。那么我的问题出在哪里呢?我也尝试过 setTimeout:

<script>
$('#btn1').click(function(){
$('#div1').addClass('show')
});

setTimeout(function() {
$('#div1').removeClass('show')
}, 2000);
</script>

我刚刚开始编程,所以我将很感激可能最容易理解的代码。感谢您的帮助。

最佳答案

使用以下内容。您实际上是在按钮单击事件之外添加超时功能。因此,它实际上在页面加载时运行,并可能在您单击按钮之前结束。

$('#btn1').click(function(){
  $('#div1').addClass('show');
  setTimeout(function(){$('#div1').removeClass('show');},2000);
});

希望这有帮助。

关于jquery - 为什么在 jquery 中添加第二个函数后我的对象没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004424/

相关文章:

html - 无论图像和文本有多长,如何使 Div 具有相同的高度?

html - 边距顶部 :-15px (negative pixels) in html not working in Outlook

javascript - 如何在React JS中获取div的高度

javascript - 如何在选中复选框的 jquery 的情况下从第一个框中克隆输入的每个输入?

jquery 在提交之前验证所有字段

javascript "this"未能定位

javascript - 运行此功能时网站崩溃

javascript - 在 html css javascript jquery 中创建导航菜单?

javascript - 模态不显示在 vue.js 中

PHP+Ajax 传递输入关键字进行实时搜索