Show/hide a div 取决于光标是否在文本字段中

Show/hide a div depending on if cursor is in a text field

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

这里有一个 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 syntax/concept 无论如何如何检测输入字段何时处于活动状态,因此它可以影响其他元素。

您可以为文本框上的 focusblur 事件创建侦听器,并将样式更新为 show/hide 和 header。下面的代码应该可以帮助您入门:

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>

希望对你有所帮助。

$('#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>