请帮我按一下按钮来停止,暂停或禁用加速度计的功能?这是我的代码谢谢。
<script>
function init() {
var accelerometer = document.getElementById('accelerometer');
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function(event) {
var x = parseInt(event.accelerationIncludingGravity.x);
var y = parseInt(event.accelerationIncludingGravity.y);
var z = parseInt(event.accelerationIncludingGravity.z);
var acce = 'Acceleration:<br />';
acce += 'x: ' + x +'<br />y: ' + y + '<br />z: ' + z + ;
accelerometer.innerHTML = acce;
});
}
}
</script>
答案 0 :(得分:2)
为.addEventListener()
提供命名函数引用,然后在.removeEventListener()
function handleAccelerationEvent(event) {
var x = parseInt(event.accelerationIncludingGravity.x);
var y = parseInt(event.accelerationIncludingGravity.y);
var z = parseInt(event.accelerationIncludingGravity.z);
var acce = 'Acceleration:<br />';
acce += 'x: ' + x +'<br />y: ' + y + '<br />z: ' + z + ;
accelerometer.innerHTML = acce;
}
function init() {
var accelerometer = document.getElementById('accelerometer');
if(window.DeviceMotionEvent) {
window.addEventListener('devicemotion', handleAccelerationEvent);
}
}
// remove `devicemotion` event referencing `handleAccelerationEvent` function
window.removeEventListener("devicemotion", handleAccelerationEvent)
答案 1 :(得分:0)
方法1:不要对侦听器使用匿名函数:将其分配给变量,以便将其传递给removeEventListener
。
方法2:不要删除监听器;相反,有一个标志,确定它是否是活动的。如果它在侦听器的顶部不活动,则返回时没有任何效果。