[英]Closing a div using the enter key
美好的一天! 我想问一下如何使用Enter键关闭div(对话框)。 我有以下代码:
<script>
function sendbutton(){
//code to make the hidden div visible upon onclick
}
</script>
<style>
.button {
height: 25px;
width: 90px;
}
.sendmessage {
height: 60%;
width: 60%;
visibility: hidden;
}
</style>
</head>
<body>
<form name="reg" id="myform">
<ul>
<li>customer first name</li>
<li><input type="text" id="userfirstname" /></li>
<li><div class="button" onclick="sendbutton(); return false;">send</div></li>
</ul>
</form>
<div class="sendmessage">
<p>your message was successfully sent!</p>
<div class="niokbutton" onclick="okbuttonsend()">ok</div>
</div>
就是这样,我希望用户填写我制作的表单,在按下send(是div)后,它将显示一条消息(我制作的div或对话框是隐藏的); 按下Enter键后如何关闭此对话框?
如果可能的话,只有javascript没有jquery。
使用jQuery:
$(document).keypress(function(e) {
if(e.which == 13) {
$('.YOURDIVCLASSNAME').hide();
}
});
没有jQuery:
<input id="yourelement" type="text" onkeypress="myFunction()">
<script>
function myFunction(event) {
if (event.which == 13 || event.keyCode == 13) {
document.getElementById("yourelement").style.display = 'none';
return false;
}
return true;
}
</script>
这适用于按键和单击,并使div可见
<script>
function sendbutton(){
// show okbuttonsend
if (document.getElementsByClassName("sendmessage")) {
document.getElementsByClassName("sendmessage")[0].style.display = 'block';
}
}
document.onkeypress = okbuttonsend;
function okbuttonsend(e) {
e = e || window.event;
// Enter key has key code 13
if (e.which == 13 || e.keyCode == 13) {
if (document.getElementsByClassName("sendmessage")) {
document.getElementsByClassName("sendmessage")[0].style.display = 'none';
return false;
}
}
return true;
}
</script>
$(function () {
$(document).keyup(function (e) {
if(e.keyCode === 13)
$('#divid').hide();
});
});
我的答案是jquery ..如果您希望div在单击时可见...只需使用
$(this).click(function(){
$('div').show();
});
要么
$(this).click(function(){
$('div').css('visibility', 'visible');
});
如果您想隐藏...只需将“可见”更改为“隐藏”
希望对您有所帮助...即使是jquery:D
其他答案: $
函数是jQuery(或Prototype),但他不希望这样。
通常<input type=submit>
可以做到。 除非焦点位于文本区域中,否则Enter键将默认发送表格。
仅按要求使用JavaScript(无Jquery):
为该框指定一个ID,以使其更易于定位:
<div id="messageBox" class="sendmessage">
<p>your message was successfully sent!</p>
<div class="niokbutton" onclick="okbuttonsend()">ok</div>
</div>
JavaScript:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 13) {
var box = document.getElementById("messageBox");
box.style.visibility="hidden";
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.