我想为按键事件制作一个二合一的解决方案。
如果我按 Enter 键,并且我的网站中没有事件的表单元素,我想提醒 AAA
。
否则提交事件表格。我该怎么做?
$(document).bind('keypress', function(e) {
if(e.keyCode==13){
e.preventDefault();
alert("AAA");
}
}); // the enter key hitted and alerted AAA
但是我如何检查表单的状态?这是一个简单的邮件发送器表单,有 4 个字段、3 个输入、1 个文本区域。
根据 Raj 的评论,这是一个很好的解决方案:
jQuery.fn.fadeToggle = function(speed, easing, callback) {
return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
var hotkeys = true;
$(document).bind('keypress', function(e) {
if((e.keyCode==13) &&(hotkeys == true)){
e.preventDefault();
$("#boxforfadein").fadeToggle();
}
});
$("form *").live("focusin", function(){
hotkeys = false;
console.log("hotkeys off");
return hotkeys;
});
$("form *").live("focusout", function(){
hotkeys = true;
console.log("hotkeys on");
return hotkeys;
});
最佳答案
使用focus 和 focusout 跟踪您的表单是否具有焦点并显示适当的警报。
还有document.activeElement 但我不太确定是否所有浏览器都支持它
关于javascript - 如果 html 站点中没有事件表单,则按 Enter 键发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6194560/