我在 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/