我有一个搜索栏,其中的结果显示在页面的中心,并带有一个固定的 div。绝对 div 用半透明的黑色覆盖结果后面的页面。如果我只是在不刷新页面的情况下删除我放入搜索字段中的内容,我怎么能删除在 keyup 函数上添加的类“.coverOn”?
谢谢。
<styles>
.coverOn {
position:absolute;
width:100%;
height:100%;
background-color:rgba(0,0,0,0.7);
z-index:8;
}
#output { /* holds search results */
position:fixed;
left:0;
right:0;
top:130px;
width:400px;
margin:0 auto;
-webkit-border-radius:15px;
-moz-border-radius:15px;
border-radius:15px;
z-index:12;
}
</styles>
<body>
<div id="cover"></div>
<div id="Search">
<input type="text" name="search" onkeyup="searchq();" value="" required class="SearchField" />
<div id="output"></div>
</div>
</body>
<script>
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("../php/productSearch.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
document.getElementById("cover").className = "coverOn";
});
}
</script>
最佳答案
如果 searchTxt
字符串为空,则删除类:
function searchq() {
var searchTxt = $("input[name='search']").val().trim();
$.post("../php/productSearch.php", {searchVal: searchTxt}, function (output) {
$("#output").html(output);
document.getElementById("cover").className = searchTxt ? "coverOn" : "";
});
}
或者因为您使用的是 jQuery,所以它可以更简单:
$("#cover").toggleClass("coverOn", searchTxt);
关于javascript - 当文本字段为空时,JS 从 div 中删除类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887822/