在移动设备上,如何防止方向变化破坏 Jquery touchstart/touchend

On mobile, how can I keep an orientation change from breaking Jquery touchstart/touchend?

本文关键字:变化 Jquery touchstart touchend 方向 何防止 移动      更新时间:2023-09-26

我这里有一个小的示例应用程序:http://codepen.io/DouglasGlover/full/OPpMaV/

这是一种仅限移动设备的体验(尽管它在技术上也可以在桌面上运行)。这里只关心手机。

预期行为是用户触摸其手机,然后将手指按住手机(屏幕上的任何位置)。当他们这样做时,计数器会上升。当他们让手指离开手机时,它会停止柜台。

有一个用例,用户可能会(可能不小心)旋转他们的手机,使网站的方向切换。目前,如果发生这种情况,计数器将继续无限向上计数。后续触摸会启动第二个触摸事件,这使它运行得更快(我可以处理这个问题,修复初始问题应该可以解决这个问题)。

所以我的问题似乎是在切换方向时,触摸事件"死亡"。所以"touchstart"最初会触发,而我正在等待一个永远不会触发的"touchend"。

理想情况下,用户可以触摸手机,然后旋转手机而不会产生任何后果(并且不会破坏体验)。

这是现在的原型代码...

.HTML:

<div class="touchspace"></div>
<div class="ls">
  <div class="counter">0</div>
</div>
<div class="pt">
  <div class="counter">0</div>
</div>

.CSS:

body{ margin: 0; }
.ls, .pt{ display: block; width: 100vw; height: 100vh; }
.ls{ background: lightblue; }
.pt{ background: lightgreen; }
.counter{ display: block; position: relative; top: 10%; font-weight: bold; color: white; font-size: 20vw; width: 20%; margin: 0 auto; }
.touchspace{ display: block; position: absolute; bottom: 0; right: 0; background: transparent; z-index: 999; background: red; width: 500vw; height: 500vh; opacity: .5; }
@media all and (orientation:landscape){ .ls{ display: none; } }
@media all and (orientation:portrait){ .pt{ display: none; } }

.JS:

var counter = 0,
interval;
$(".touchspace").bind("touchstart mousedown",function(){
  interval = window.setInterval(function(){
    counter++;
    $(".counter").html(counter);
  }, 1000);
});
$(".touchspace").bind("touchend mouseup",function(){
  window.clearInterval(interval);
});

您能否绑定方向更改事件以触发结束和开始,或者这会导致用户体验中断太多。

像这样:

$(window).on('orientationchange', function () {
   $('.touchspace').trigger('touchend');
   $('.touchspace').trigger('touchstart');
});

在间隔内,检查初始方向是否更改并清除间隔。无法测试代码,因为我没有环境!

var counter = 0,
isOrientationChanged=false,
interval;
$(".touchspace").bind("touchstart mousedown",function(){
  interval = window.setInterval(function(){
    counter++;
    $(".counter").html(counter);
    //check if orientation is changed, clear the interval & reset the flag
    if(isOrientationChanged)
    { 
        isOrientationChanged=false;
        window.clearInterval(interval);
    }
  }, 1000);
});
$(".touchspace").bind("touchend mouseup",function(){
  window.clearInterval(interval);
});
$(window).on('orientationchange', function () {
  isOrientationChanged=true;//mark the flag true
});

我花了 2 个小时试图实现它。似乎现在无法 - 当前的艺术先验。"方向更改"会失去元素的焦点。