如何在Javascript/jQuery中隐藏和显示元素

How to hide and show element in Javascript/jQuery on keydown OR click?

本文关键字:隐藏 显示 元素 jQuery Javascript      更新时间:2023-09-26

我试图隐藏和显示一个带有keydown事件的输入框,但如果在输入框外单击,我不知道如何执行同样的操作。

HTML:

        <header>
        <h1>Hello {{visitorInput}}!</h1>
        <h4 id="greet">Nice to see you :)</h4>
        <form action="#">
            <input type="text" ng-model="visitorInput" id="visitorInput" placeholder="Please enter your name and press Enter.">
        </form>
    </header>

Javascript/jQuery:

var visitorInput = document.getElementById("visitorInput");
$('#visitorInput').focus();
    $('#visitorInput').keydown(function( event ){
        if(event.which == 13){
                $("#greet").show();
                console.log('Visitor name is: ' + visitorInput.value);
                //alert('Visitor name is: ' + visitorInput.value);
                $("#visitorInput").hide();
                    $('#greet, h1').click(function(){
                        $('#visitorInput').show().focus();
                        $('#greet').hide();
                    });
        };
    });

使用以下编码

var visitorInput = document.getElementById("visitorInput");
$('#visitorInput').focus();
    $('#visitorInput').keydown(function( event ){
        if(event.which == 13){
                $("#greet").show();
                console.log('Visitor name is: ' + visitorInput.value);
                //alert('Visitor name is: ' + visitorInput.value);
                $("#visitorInput").hide();
        };
    });
$('#greet, h1').click(function(){
                            $('#visitorInput').show().focus();
                            $('#greet').hide();
      });

在按键事件编码之外应用点击事件

您在一条评论中表示,keydown可以按照您的意愿工作,所以我只简化了那里的代码,并保留了功能,尽管它对我来说确实是一个奇怪的用户体验,所以我认为这里没有显示更多内容。

关于当用户点击退出时使输入消失,您需要.blur()

var $visitorInput = $('#visitorInput').focus();
$visitorInput.keydown(function(event) {
  if (event.which == 13) {
    var $greet=$("#greet").show();
    console.log('Visitor name is: ' + visitorInput.value);
    $visitorInput.hide();
    $("#greet, h1").click(function() {
      $visitorInput.show().focus();
      $greet.hide();
    });
  };
}).blur(function(event) {
  $visitorInput.hide();
});
#greet {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <h1>Hello {{visitorInput}}!</h1>
  <h4 id="greet">Nice to see you :)</h4>
    <input type="text" ng-model="visitorInput" id="visitorInput" placeholder="Please enter your name and press Enter.">
</header>