我知道 Stackoverflow 中也有很多类似的问题。这是一些 Jquery 问题。我添加了切换类 Jquery 函数,当单击正文的任何位置时应删除相同的类。它现在可以工作了,但是当我们在输入文本字段中单击时,我不需要切换该类。
代码:
var removeClass = true;
$(".btn-search").click(function() {
$(".input-search").toggleClass('expanded');
removeClass = false;
});
$("html").click(function() {
if (removeClass) {
$(".input-search").removeClass('expanded');
}
removeClass = true;
});
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;
}
<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>
最佳答案
要解决此问题,您可以检查哪个元素引发了使 DOM 冒泡的点击事件。如果它不在 .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');
});
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;
}
<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>
关于javascript - 点击正文切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697192/