发现requestPointerLock只能在其他事件的响应函数中生效,直接在同步代码中执行和在requestAnimationFrame中执行都不生效,同时既没有报错也不会触发pointerlockerror事件。
请问requestPointerLock生效的条件究竟是什么?
下面是一个测试页面,requestPointerLock生效时鼠标会消失。
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>TestLock</title>
6 </head>
7 <body oncontextmenu="return false;">
8 <div style="width: 500px;height: 500px" id="div_test">
9
10 </div>
11 </body>
12 </html>
13 <script>
14
15
16 div_test=document.getElementById("div_test");
17 div_test.requestPointerLock = div_test.requestPointerLock || div_test.msRequestPointerLock || div_test.mozRequestPointerLock || div_test.webkitRequestPointerLock;
18
19
20 var pointerlockchange = function (event) {
21
22
23 var controlEnabled = (document.mozPointerLockElement === div_test || document.webkitPointerLockElement === div_test || document.msPointerLockElement === div_test || document.pointerLockElement === div_test);
24 if (!controlEnabled) {
25
26 console.log("1");
27 } else {
28 console.log("2");
29 }
30 //}
31 };
32 document.addEventListener("pointerlockchange", pointerlockchange, false);
33 document.addEventListener("mspointerlockchange", pointerlockchange, false);
34 document.addEventListener("mozpointerlockchange", pointerlockchange, false);
35 document.addEventListener("webkitpointerlockchange", pointerlockchange, false);
36 document.addEventListener("pointerlockerror ", pointerlockchange, false);
37 function lock()
38 {
39 if (div_test.requestPointerLock) {
40 div_test.requestPointerLock();//但是如果这一句是在调试中运行的,就不能起作用了,因为光标在另一个页面中!!
41 }
42 }
43 lock();
44
45 window.requestAnimFrame = (function() {
46 return window.requestAnimationFrame ||
47 window.webkitRequestAnimationFrame ||
48 window.mozRequestAnimationFrame ||
49 window.oRequestAnimationFrame ||
50 window.msRequestAnimationFrame ||
51 function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
52 window.setTimeout(callback, 1000/60);
53 };
54 })();
55 requestAnimFrame(lock);
56
57 div_test.addEventListener("click", function(evt) {
58
59 if(evt.button==2)//右键单击
60 {
61 lock();
62 }
63 else if(evt.button==0)
64 {
65 lock();
66 }
67 }, false);
68
69
70 </script>来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4715/viewspace-3127884/ ,如需转载,请注明出处,否则将追究法律责任。