我想在我的 ajax 搜索时将加载图像显示为叠加 div。
我的代码
<script>
function showHint(str) {
if (str.length==0) {
document.getElementById("result").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","search_result.php?q="+str,true);
xmlhttp.send();
}
</script>
<input name="keyword" id="keyword" type="text" onkeyup="showHint(this.value)""/>
结果显示在此表中
<div class="table-wrapper">
<table class="openings" id="result">
</table>
</div>
我当前的代码正确地显示在这个表中,但只需要添加一个覆盖加载。
此外,当我搜索任何内容时,它会正确显示,但在键入后,如果我从框中删除搜索关键字,则结果区域将为空白。
最佳答案
您可以使用普通的 javascript 和 CSS 执行以下操作:
**[JAVASCRIPT]**
<script type="text/javascript">
function showLoadingImage(visible){
document.getElementById("loader").style.visibility = visible ? "visible" : "hidden";
}
function showHint(str) {
if (str.length==0) {
document.getElementById("result").innerHTML="";
return;
}
showLoadingImage(true);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML=xmlhttp.responseText;
showLoadingImage(false);
}
}
xmlhttp.open("GET","search_result.php?q="+str,true);
xmlhttp.send();
}
</script>
**CSS**
<style type="text/css">
#loader{
position:fixed;
width:100%;
height:100%;
display:table;
visibility:hidden;
background-color: rgba(0,0,0.6);
}
#loader .inner{
display: table-cell;
vertical-align:middle;
}
</style>
**[HTML]**
<div id="loader">
<div class="inner">
<img src="loader.gif">
</div>
</div>
在上面的示例中,当您执行“showHint”函数时,会显示加载器 div,覆盖屏幕,并且您的加载器图像会显示在屏幕中间。当然,您可以更改 div#loader 背景颜色,并根据需要进行一般配置。
关于javascript - 如何设置覆盖 div 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23661208/