简体   繁体   English

Jquery 点击输入框显示div,点击正文隐藏div

[英]Jquery click input field show div, click body hide div

I have an input field when you click on it, it will show/display a div below it.当您单击它时,我有一个输入字段,它会在其下方显示/显示一个 div。

Once the div is displaying, if you click in the div the div will remain showing (display block), and if you click off the div (on the body) the div will disappear (display none).一旦 div 正在显示,如果您在 div 中单击,div 将保持显示(显示块),如果您单击 div(在正文上),div 将消失(不显示)。

    $("#input-field").click(function() {
       $("#div").show();
       $("#div").ready(function(){
          if ($('#div').css('display') == 'block')
             {
                $(document).click(function(e) {
                    if (e.target.id != 'div' && !$('#div').find(e.target).length) {
                        $("#div").hide();
                    }
                });
             }
       });
    });  

Problem is, this works fine one single time (click on the input field, the div shows, then click on the body and the div disappears), but if I click back on the input field nothing happens.问题是,这一次工作正常(单击输入字段,div 显示,然后单击正文,div 消失),但如果我再次单击输入字段,则没有任何反应。

I've been wrestling with this for hours...我已经为此苦苦挣扎了几个小时......

https://jsfiddle.net/n8671asp/1/ https://jsfiddle.net/n8671asp/1/

Just change the event click to mouseup .只需将事件click更改为mouseup Hope it will work.希望它会起作用。

$(document).mouseup(function(e) {
    if (e.target.id != 'div' && !$('#div').find(e.target).length) {
        $("#div").hide();
    }
});

You might not want this, but instead of seeing if the target is not the input, how about you just focus on .focus() and .focusout() ?您可能不想要这个,但是与其查看目标是否不是输入,不如只关注.focus().focusout()怎么样? These functions control when you can type in the input and when you cannot.这些函数控制什么时候可以输入,什么时候不能输入。

 $("#input-field").focus(function() { $("#div").show(); }); $("#input-field").focusout(function(e) { $("#div").hide(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- example HTML --> <div id="div">I'm the div</div> <input val="input to click" id="input-field">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM