【问题标题】:iOS touches to device's viewport x/y coordinates via JavascriptiOS 通过 Javascript 触摸设备的视口 x/y 坐标
【发布时间】:2012-12-20 02:53:13
【问题描述】:

我目前正在为 iPhone 开发一个网页,其中包含一个用户可以触摸和拖动的 DIV 元素。另外,当用户将元素拖到设备屏幕的顶部或底部时,我想自动向上或向下滚动页面。

我遇到的问题是试图确定一个可靠的公式来获取 onTouchMove 事件中的坐标,该坐标与用户的手指到达设备视口的顶部或底部相一致。我目前的公式似乎很乏味,我觉得可能有更简单的方法来做到这一点。

我目前判断触摸事件是否到达屏幕底部的公式:

function onTouchMoveHandler(e)
{
    var orientation=parent.window.orientation;
    var landscape=(orientation==0 || orientation==180)?true:false;
    var touchoffsety=(!landscape?screen.height - (screen.height - screen.availHeight):screen.width - (screen.width - screen.availWidth)) - e.touches[0].screenY + (window.pageYOffset * .8);
    if(touchoffsety < 40) alert('finger is heading off the bottom of the screen');
}

我对窗口、文档、正文、e.touches 等对象进行了一些 Javascript 反射,看看我是否能找到一组总加起来等于屏幕顶部或底部的数字,但没有可靠的成功。非常感谢您的帮助。

【问题讨论】:

标签: javascript iphone ios touch viewport


【解决方案1】:

假设触摸的 screenY 字段保持相对于屏幕顶部的 y 坐标,无论当前滚动位置如何,您当前的计算对我来说没有多大意义。我希望我没有误解你的意图。

要确定触摸是靠近设备顶部还是底部,我首先会检查 screenY 是否靠近顶部(顶部为 0),因为您可以直接使用该值。然后,如果它不靠近顶部,则计算它与底部的距离并检查。

var touch = e.touches[0];
if (touch.screenY < 50)
{
    alert("Closing in on Top");
}
else //Only do bottom calculations if needed
{
    var orientation=parent.window.orientation;
    var landscape=(orientation==0 || orientation==180)?true:false;
    //height - (height - availHeight) is the same as just using availHeight, so just get the screen height like this
    var screenHeight = !landscape ? screen.availHeight : screen.availWidth;
    var bottomOffset = screenHeight - touch.screenY; //Get the distance of the touch from the bottom
    if (bottomOffset < 50)
        alert("Closing in on Bottom");
}

【讨论】:

  • 这是我遇到的问题之一。有人会认为 screenY 就是您所需要的,但事实并非如此。一个原因是,如果您有两个 iFrame,并且在底部 iFrame 中拖动一个 DIV,则数字似乎会根据您当前滚动的距离而倾斜。这就是 window.pageYOffset 发挥作用的地方,它告诉浏览器窗口向下滚动多远。但根据滚动到的位置,它似乎会过度或不足补偿正确的数量。这就是为什么我把它乘以 0.8 来捏造它,但它仍然很挑剔。
  • 你试过clientY了吗?也许这对你也有帮助:stackoverflow.com/questions/5885808/…
  • 过完年回到办公室,我会试试你引用的那篇文章。这看起来很有希望。这可能是一个错误的事实是有道理的,而且这个人可能已经弄清楚了这个错误以及如何解决它......
  • 这篇文章没有任何帮助。但是你可能会对 screenY 感兴趣。我现在正在使用 iPad 进行测试,发现 screenY 是浏览器顶部地址栏结束处的屏幕坐标。如果您触摸地址栏或地址栏上方,您实际上会得到一个 NEGATIVE screenY 值。 screen.availHeight 包括地址栏大小,因此让我很伤心。但是,我发现 window.outerHeight 不包括地址栏。所以公式 window.outerHeight - touch.screenY 似乎可以找到接近底部的触摸。明天我会测试 iphone。
【解决方案2】:

这其实还不错。你也可以使用 Zepto.js 及其内置的触摸事件和.offset() 方法让它变得更简单:

但是,我很想知道您是否真的设法让它在底部滚动,以及性能是否足够平滑以使效果值得。 (在 iOS 中频繁滚动会严重中断 JavaScript)

【讨论】:

  • 我使用 window.outerHeight - touch.screenY
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 1970-01-01
相关资源
最近更新 更多