在点击主体上切换类

vis*_*hnu 2 html javascript css jquery

我知道很多类似的问题也在Stackoverflow中.这是一个Jquery问题.我添加了toggle类Jquery函数,并且当单击body上的任何位置时应该删除相同的类.它现在正在工作,但是当我们点击输入文本字段内部时,我不需要切换该类.

码:

var removeClass = true;
$(".btn-search").click(function() {
  $(".input-search").toggleClass('expanded');
  removeClass = false;
});
$("html").click(function() {
  if (removeClass) {
    $(".input-search").removeClass('expanded');
  }
  removeClass = true;
});
Run Code Online (Sandbox Code Playgroud)
body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color:#fff;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">
</div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴:https://jsfiddle.net/vishnuprasadps/3a84p6h0/

Ror*_*san 7

要解决此问题,您可以检查哪个元素引发了冒泡DOM的click事件.如果它不在那之内,.col-search你可以切换课程.

另请注意,此逻辑会使您的removeClass变量冗余.

$(".btn-search").click(function(e) {
  e.stopPropagation();
  $(".input-search").toggleClass('expanded');
});

$("html").click(function(e) {
  if ($(e.target).closest('.col-search').length == 0)
    $(".input-search").removeClass('expanded');
});
Run Code Online (Sandbox Code Playgroud)
body {
  background: #eee;
}

.col-search {
  padding: 13px 8px 8px 0;
  position: relative;
  width: 80%;
}

.input-search {
  width: 220px;
  height: 34px;
  max-width: 0;
  padding: 5px 10px;
  transition: all .2s ease;
  position: absolute;
  top: 13px;
  bottom: 13px;
  right: 46px;
  border: 0;
  box-sizing: border-box;
  opacity: 0;
}

.input-search.expanded {
  max-width: 220px;
  opacity: 1;
}

.btn-search {
  position: absolute;
  right: 0;
  width: 38px;
  height: 34px;
  border: 0;
  background: #333;
  color: #fff;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="col-search">
  <input class="input-search" type="search" placeholder="Search" />
  <input type="button" class="btn-search" value="click">
</div>
Run Code Online (Sandbox Code Playgroud)