CSS 和 JS - 试图获取"livesearch"结果显示为浮动下拉列表,而不是推开周围的内容



我使用W3CSS和一些JavaScript在我的网站顶部有一个实时搜索栏-我需要搜索栏在用户键入时显示结果-但我需要在其他内容的顶部显示结果。现在他们在推送其他内容,我不知道该如何阻止。正如我所提到的,我使用的是W3CSS,我尝试将包含我的结果的div设置为使用class="3-dropdown content w3 bar block",但结果是完全不可见的。非常感谢您的帮助!

这是我的HTML

<!-- NAV HEADER -->
<div class='w3-top'>
<div class='w3-bar w3-light-grey'>
<a href='home.php' class='w3-bar-item w3-button'><i class='material-icons'>home</i></a> 
<a href='view_customer.php' class='w3-bar-item w3-button'>Customers</a>
<a href='tickets.php' class='w3-bar-item w3-button'>Tickets</a>
<a href='info.php' class='w3-bar-item w3-button'>Info</a>
<a href='#' class='w3-bar-item w3-button'>Reports</a>
<input type='text' class='w3-bar-item w3-input' placeholder='Search..' onkeyup='showResult(this.value)'>
<div id='livesearch'></div>
<a href='#' class='w3-bar-item w3-button'><i class='material-icons'>calendar_today</i></a>
<a href='#' class='w3-bar-item w3-button'><i class='material-icons'>settings</i></a>
<a href='#' class='w3-bar-item w3-button'><i class='material-icons'>notifications_none</i></a>
<a href='#' class='w3-bar-item w3-button'><i class='material-icons'>person</i>Employee Name /</a>
</div>
</div>

这是我的JavaScript:

function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {  // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}

看,你只是把响应放在代码中,1什么都不做,2尝试使用类似的fetch方法

function showResult(str) {
fetch("livesearch.php?q="+str)
.then(response => response.text())
.then(function(response){
document.getElementById("livesearch").innerHTML= response;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
});
}

这是你的代码的一个较小版本,它应该像一个魅力一样工作

我想这可能是一个解决方案:

(...) 
<a href='#' class='w3-bar-item w3-button'>Reports</a>
<div class='w3-dropdown w3-bar-item'>
<input type='text' class=' w3-input' placeholder='Search..' onkeyup='showResult(this.value)'>
<div id='livesearch' class="w3-border w3-dropdown-content "></div>
</div>  
<a href='#' class='w3-bar-item w3-button'><i class='material-icons'>calendar_today</i></a>
(...)

为了显示dropdwon,您的函数必须添加类";w3节目";到div";livesearch";并在你想隐藏这个类时将其删除。

最新更新