代码之家  ›  专栏  ›  技术社区  ›  Matthias Güntert

如何隐藏元素并仅在用户开始键入时显示它?

  •  2
  • Matthias Güntert  · 技术社区  · 5 年前

    我正在尝试将搜索功能整合到我的Jekyll网站中。因此,我决定 Simple-Jekyll-Search 可在此处找到: Link

    这是我的 search.html 看起来像:

    <input type="text" id="my-search-input" placeholder="Search">
    
    <div class="card">  
      <ul id="my-results-container"></ul>
    </div>
    
    <script src="/assets/javascript/simple-jekyll-search.min.js" type="text/javascript"></script>
    
    <script>
    SimpleJekyllSearch({
      searchInput: document.getElementById('my-search-input'),
      resultsContainer: document.getElementById('my-results-container'),
      searchResultTemplate: '[...]',
      json: '/search.json',
      noResultsText: '<li><p>No results found!</p></li>'
    })
    </script>
    

    到目前为止,搜索功能工作得很好。但是,即使没有输入任何内容,也会显示带边框的卡。所以问题是:

    如何隐藏卡片并仅在用户输入一些按键后显示?

    enter image description here

    2 回复  |  直到 5 年前
        1
  •  2
  •   lalitrane    5 年前

    首先在样式表中隐藏卡片类。

    .card{
    
    display:none;
    }
    

    然后在脚本标记中添加以下代码-

    $(function() {
         $('#my-search-input').keyup(function() {
     if ($(this).val().length == 0) {
    
        $('.card').hide();
      } else {
        $('.card').show();
      }
    }).keyup();
    });
    

    我假设您已经在代码中添加了jquery,如果没有,请在head标记中添加以下代码

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
        2
  •  1
  •   keanu_reeves    5 年前

    我会这样做(非jquery方式):

    function show(){
    //Get the div we want gone/appeared
    box=document.getElementById("box");
    //Get the input
    input=document.getElementById("input");
    
    //Check if the user enterred something
    if(!input.value==""){
      //If its the case set the box to visible
      box.style.display="block";
    }else{
      //Else we want it gone
      box.style.display="none";
    }
    }
    /*SO related*/
    body{background:#121212;color:white;font-family:Helvetica, sans-serif;}
    
    /*SO related*/
    #input{
    background:#222222;
    color:white;
    padding:5px;
    border:1px solid white;
    }
    
    /*Important*/
    #box{
    display:none;
    /*SO related*/
    border:1px solid white;
    }
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <p>Enter something silly:</p>
    <input type="text" id="input" onkeyup="show();">
    <div id="box">wow look i popped out</div>
    </body>
    </html>