2013-08-01 65 views
1

我試圖在用戶同時按下「Space」和「Enter」鍵時在我的網頁上提供全屏選項。我有以下代碼。我有以下代碼。但它不起作用。我哪裏錯了?如果我提供一個密鑰,它正在工作。全屏選項

<!doctype html> 
<html> 
<head> 
    <title>Full Screen Example</title> 
    <style type="text/css"> 
     :-webkit-full-screen #myimage { 
     width: 100%; 
     height: 100%; 
    } 
    </style> 
</head> 
<body> 
    <p>Press "space" and "enter" to enter full screen</p> 
    <p><strong>To use full-screen mode, you need Firefox 9 or later or Chrome 15 or   later.</strong></p> 
    <img src = "./3.jpg" width="640" height="360" id="myimage"> 
</body> 
<script> 
var imageElement = document.getElementById("myimage"); 

function toggleFullScreen() { 
    if (!document.mozFullScreen && !document.webkitFullScreen) { 
     if (imageElement.mozRequestFullScreen) { 
      imageElement.mozRequestFullScreen(); 
     } else { 
      imageElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); 
     } 
    } else { 
     if (document.mozCancelFullScreen) { 
      document.mozCancelFullScreen(); 
     } else { 
      document.webkitCancelFullScreen(); 
     } 
    } 
} 

document.addEventListener("keydown", function(e) { 
    if ((e.keyCode == 13) && (e.keyCode == 32)) { 
     toggleFullScreen(); 
    } 
}, false); 
</script> 

回答

1

刪除當前的addEventListener()調用,並用我在下面提供的內容來擴充腳本。請注意,這在IE8中不起作用(但考慮到您正在使用moz和webkit功能,我想你不會將它定位到任何地方)。

var keys = []; 

function keyIsDown(keyCode) { 
    return (keys.indexOf(keyCode) > -1); 
} 

document.addEventListener("keydown", function(e) { 
    // Remember the key being pressed 
    keys.push(e.keyCode); 

    // Check if ENTER and SPACE are both being pressed 
    if (keyIsDown(13) && keyIsDown(32)) { 
    toggleFullScreen(); 
    } 
}, false); 

document.addEventListener("keyup", function(e) { 
    // Remember that this key is no longer being pressed 
    var keyIndex = keys.indexOf(e.keyCode); 
    if (keyIndex > -1) keys.splice(keyIndex, 1); 
}, false); 

感謝parjun的基本想法;我只是沒有jQuery就完成了。

0

您需要維護一組正在按下的鍵和正在釋放的鍵。

var keyArray = []; 
function containsAll(firstArray, secondArray){ 
    for(var i = 0 , len = firstArray.length; i < len; i++){ 
    if($.inArray(firstArray[i], secondArray) == -1) return false; 
    } 
    return true; 
} 
document.addEventListener("keydown", function(e) { 
     if ((e.keyCode == 13) || (e.keyCode == 32)) { 
     keyArray.push(e.keyCode); 
     } 
    if(containsAll(['13','32'],keyArray)){ 
toggleFullScreen(); 
} 

    }, false); 
$(document).keyup(function (e) { 
    keyArray.remove(e.keyCode); 
}); 
+0

沒有工作............................ – Benny