我有一些Javascript让空格键暂停播放的歌曲。但是“event.stopInmediatePropagation();似乎不起作用...... 我想使用此函数忽略表单或其他内容时的键盘操作.... 我正在使用Bootstrap ...
这是我的代码:
$('form').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '32'){
}
event.stopImmediatePropagation();
});
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '32'){
if($('#play').is(":visible")){
playNextSong(0);
}
else{
pause();
}
}
});
答案 0 :(得分:0)
我不确定您的代码有什么问题,但您的代码在我的演示文稿中有效。
$('form').keypress(function (event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '32') {
$("#output").append("space pressed in form<br/>");
}
event.stopImmediatePropagation();
});
$(document).keypress(function (event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '32') {
console.log("pressed space");
$("#output").append("space pressed outside of form.<br/>");
if ($('#play').is(":visible")) {
playNextSong(0);
} else {
//console.log('pause');
//pause();
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" />
</form>
<div id="output"></div>
&#13;
答案 1 :(得分:0)
如果您使用可见性隐藏播放按钮,则需要使用$('#play').css("visibility") == "visible"
检查元素是否可见
$('form').keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '32') {}
event.stopPropagation();
});
$(document).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '32') {
if ($('#play').css("visibility") == "visible") {
//playNextSong(0);
$('#play').css("visibility", "hidden");
} else {
//pause();
$('#play').css("visibility", "visible");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="play">Play</div>
<form action="">
<input type="text" />
</form>