显示加载gif onkeypress

时间:2016-11-11 23:40:17

标签: javascript gif onkeypress

所以我有一个输入和dataList:

<div id="namearea">
        <h2>City Name:</h2>

        <div>
            <input id="citiesinput" list="cities">
            <datalist id="cities"></datalist>

            <button id="search">
                Search
            </button>

            <span class="loading" id="loadingnames">
                <img src="/gif" alt="icon" />
                Loading...
            </span>
        </div>
    </div>

我已经使用JS用data选项填充dataList。

我想要做的是显示从我开始输入输入时的加载gif,直到我选择了一个选项或按下搜索按钮

目前的JS:

var cityArray;

window.onload = function() {
    processCities();

    document.getElementById("search").onclick = findWeather;
    document.getElementById("citiesinput").addEventListener("onkeypress", showLoad);


};

function showLoad () {
    var input = document.getElementById("citiesinput").value;
    if(input !== "" || cityArray.indexOf(input) == -1) {
        document.getElementById("loadingnames").style.display = "block";
    }
}

2 个答案:

答案 0 :(得分:0)

我为你准备了一个小提琴here。我使用keyup事件,因为在输入值中注册了第一个键之前调用了keypress事件。

input.addEventListener('keyup', function(){
    loading.style.display = input.value.length ? 'block' : 'none';
});

如果不满足条件,您还必须记住删除加载程序。

答案 1 :(得分:0)

  • 使用不透明度而不是显示。原因是当您将显示设置为内联块时,您会发现您的父div“故障”其高度以将其内容调整为图像div

  • 按键后使用键盘事件,将触发功能

    var cityArray;
    cityArray = ["city1", "city2"]
    
    function findWeather() {
    
    }
    window.onload = function() {
      //processCities();
    
      //document.getElementById("search").onclick = findWeather;
      document.getElementById("citiesinput").addEventListener("keyup", showLoad);
      document.getElementById("search").addEventListener("click", showLoad);
    
    
    };
    
    function showLoad() {
      var input = document.getElementById("citiesinput").value.trim();
      if (input == "") {
        document.getElementById("loadingnames").style.opacity = "0";
        return
      }
      if (cityArray.indexOf(input) == -1) {
        document.getElementById("loadingnames").style.opacity = "1";
      } else {
        document.getElementById("loadingnames").style.opacity = "0";
      }
    }
    <div id="namearea">
      <h2>City Name:</h2>
    
      <div>
        <input id="citiesinput" list="cities">
        <datalist id="cities"></datalist>
    
        <button id="search">
          Search
        </button>
    
        <span class="loading" id="loadingnames" style="opacity:0;">
        <img src="http://bestwallpaperhd.com/wp-content/uploads/2012/12/animated-wallpaper-gif.gif" alt="icon " id="city_img " style="width:50px;height:50px;"/>Loading...
        </span>
      </div>
    </div>