使用jquery添加带时间限制的删除类

时间:2015-09-10 06:04:29

标签: jquery

我有一个搜索框,只能在点击图标时显示。 单击图标后出现该框后,即使用户单击身体的其他部分,它也会在某个时间间隔(例如5秒)内消失。

$(".icon").click(function()){
    $("search-box").addClass("active");
});

2 个答案:

答案 0 :(得分:1)

你正在寻找这个吗?

<强> Jquery的

var icon = $(".icon");
icon.click(function () {
    $(".search-box").addClass("active");
    setTimeout(function () {
        icon.fadeOut();
    }, 5000)
})

答案 1 :(得分:1)

做这样的事情

var box = $(".search-box");

// Code for closing if anywhere else is clicked
$(document).click(function() {
  box.removeClass('active');
});

$(".icon").click(function(e) {
  e.stopPropagation();
  // preventing parent click handler 

  box.addClass("active");
  // Adding class to the box

  setTimeout(function() {
    box.removeClass('active');
  }, 5000)
  // Code for removing class after 5 second
 
})

box.click(function(e) {
  e.stopPropagation();
  // preventing parent click handler 
});
.search-box {
  display: none
}
.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="icon">click</button>

<div class="search-box">Box to display</div>