【问题标题】:Show/hide a div depending on if cursor is in a text field根据光标是否在文本字段中显示/隐藏 div
【发布时间】:2021-02-20 04:28:44
【问题描述】:

我有一个输入文本字段,它上面有一个格式栏。 当光标不在输入字段中时,我想隐藏栏。

这里有一个Jsfiddle 给任何能够提供帮助的人。

<div class="header-div">
This is my header div
</div>

<div >
<input placeholder="placeholder text">
</div>

<p class="explainer">
When I've clicked in the input box above (ready to type or currently typing), I want the grey bar above to show, otherwise hide it.
</p>

请注意,我使用 Quill 进行富文本输入,但只是想知道如何检测输入字段何时处于活动状态的一般 javascript 语法/概念,因此它可能会影响其他元素。

【问题讨论】:

    标签: javascript input textarea show-hide quill


    【解决方案1】:

    您可以为文本框上的focusblur 事件创建侦听器,并更新样式以显示/隐藏标题。下面的代码应该可以帮助您入门:

    let textbox = document.querySelector('input');
    let header = document.querySelector('.header-div');
    
    // add event listeners to textbox
    textbox.addEventListener('focus', function() { 
        toggleDisplay(header, true);
    });
    textbox.addEventListener('blur', function() { 
        toggleDisplay(header, false);
    });
    
    function toggleDisplay(element, show) {
        if (show) 
            element.style.display = 'block';
        else
            element.style.display = 'none';
    }
    .header-div {
      display: none;
      background-color: #ccc;
      padding: 8px;
      border-radius:6px;
      margin-bottom:8px;
    }
    
    .explainer {
      color:#aaa;
    }
    <div class="header-div">
      This is my header div
    </div>
    
    <div >
      <input placeholder="placeholder text">
    </div>
    
    <p class="explainer">
      When I've clicked in the input box (ready to type or currently typing), I want   the grey bar above to show, otherwise hide it.
    </p>

    【讨论】:

      【解决方案2】:

      希望对你有帮助。

      $('#myinp').on('focus blur',function(e){
      if(e.type=='focus'){
      $('.header-div').css('display','block');
      }else{
      $('.header-div').css('display','none');
      }
      });
      .header-div{
        display:none;
        background-color: #ccc;
        padding: 8px;
        border-radius:6px;
        margin-bottom:8px;
      }
      .explainer{
        color:#aaa;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div class="header-div">
      This is my header div
      </div>
      
      <div >
      <input id='myinp' placeholder="placeholder text">
      </div>
      
      <p class="explainer">
      When I've clicked in the input box (ready to type or currently typing), I want the grey bar above to show, otherwise hide it.
      </p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        • 2015-12-21
        • 1970-01-01
        • 2011-04-09
        • 2016-12-22
        • 2021-02-22
        相关资源
        最近更新 更多