[英]How to hide and show element in Javascript/jQuery on keydown OR click?
我正在嘗試隱藏和顯示帶有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事件編碼之外應用click事件
您在評論中指出,keydown可以按您希望的方式工作,因此我只簡化了一點代碼,只保留了功能,盡管對我來說這似乎是一個奇怪的UX,所以Im認為您還需要更多功能在這里顯示。
關於在用戶單擊時使輸入消失,您需要.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.