我想在一定时间后自动淡入div onclick和淡出div

时间:2018-07-09 10:54:02

标签: javascript jquery alert fadein fadeout

实际上,我的问题是,我想在fadein事件中div click,并在一段时间后自动fadeout div

我做了一些事情,但是fadeout函数无法正常工作。这是我的代码段:

.alert-box {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  display: none;
  padding: 20px 0;
  background-color: red;
  color: #fff;
}

.close {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button>click me</button>


<div class="alert-box">
  <span class="close">&times;</span>
  <div class="content">
    sample content
  </div>
</div>


<script type="text/javascript">
  $(document).ready(function() {
    $('button').click(function() {
      $('.alert-box').fadeIn('fast');
    });
    if ($('.alert-box').css('display') == 'block') {
      $('.alert-box').delay(1000).fadeOut('fast');
    }
  });
</script>

2 个答案:

答案 0 :(得分:3)

使用setTimeout进行1秒后的淡入淡出

setTimeout (() => {
    $('.alert-box').fadeOut('fast');
}, 1000)

也删除了不必要的代码。

.alert-box {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  display: none;
  padding: 20px 0;
  background-color: red;
  color: #fff;
}

.close {
  position: absolute;
  right: 10px;
  top: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>click me</button>


<div class="alert-box">
  <span class="close">&times;</span>
  <div class="content">
    sample content
  </div>
</div>


<script type="text/javascript">
  $(document).ready(function() {
    $('button').click(function() {
      $('.alert-box').fadeIn('fast');
      setTimeout(() => {
        if ($('.alert-box').css('display') == 'block') {
          $('.alert-box').delay(1000).fadeOut('fast');
        }
      }, 1000);
    });

  });
</script>

答案 1 :(得分:2)

您可以在fadeOut()之后立即使用fadeIn(),以提高延迟速度。

$(document).ready(function() {
    $('button').click(function() {
        $('.alert-box').fadeIn('fast').delay(1000).fadeOut('fast');
    });
});
.alert-box{
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        display: none;
        padding: 20px 0;
        background-color: red;
        color: #fff;
    }
    .close{
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click me</button>


<div class="alert-box">
    <span class="close">&times;</span>
    <div class="content">
        sample content
    </div>
</div>