gpt4 book ai didi

javascript - UIWebView、缩放和 elementFromPoint

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:40 24 4
gpt4 key购买 nike

UIWebView 中,当我长按它时,我需要访问 DOM 元素的属性(从 SVG 图形)。为此,我添加了一个 UILongPressGestureRecognizer,如下所示:

UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action: @selector(longPress:)];
[self.webView addGestureRecognizer: longPress];

当我在 View 上长按时,会调用处理程序,我从中调用一个 JS 函数:

- (void) longPress: (UIGestureRecognizer *) gesture {
CGPoint curCoords = [gesture locationInView:self.webView];

if (!CGPointEqualToPoint(curCoords, self.lastLongPress)) {
self.lastLongPress = curCoords;
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"longPress(%f, %f)", curCoords.x, curCoords.y]];
}
}

这是我的 JS 处理程序:

function longPress(x, y) {

x = x + window.pageXOffset;
y = y + window.pageYOffset;

var element = svgDocument.elementFromPoint(x, y);
alert(element.localName + ' ' + x + ' ' + y + ' ' + window.innerWidth + ' ' + window.innerHeight);
}

但是,UIWebView 坐标似乎是 != 来自 DOM 坐标(我单击的位置与警报中显示的 localName 不对应)。我设法弄清楚 UIWebView 坐标和 JS 坐标之间有 +/- 1.4 的系数(通过单击屏幕右下角并将这些值与 进行比较window.innder{Width,Height}.

我的猜测是 UIWebView 最初可能会应用默认缩放比例,但我找不到该值对应的值。

此外,我还需要一种方法来在用户实际缩放/移动页面时使这项工作正常进行。

有人知道我做错了什么吗?

谢谢,

最佳答案

好吧,我终于找到问题所在了。

它来自缩放比例,这是我设法修复它的方法:

- (void) longPress: (UIGestureRecognizer *) gesture {
int displayWidth = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] intValue];
CGFloat scale = self.webView.frame.size.width / displayWidth;

CGPoint curCoords = [gesture locationInView:self.webView];

curCoords.x /= scale;
curCoords.y /= scale;

if (!CGPointEqualToPoint(curCoords, self.lastLongPress)) {
self.lastLongPress = curCoords;

[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"longPress(%f, %f)", curCoords.x, curCoords.y]];
}
}

和 JS 处理程序:

function longPress(x, y) {
var e = svgDocument.elementFromPoint(x, y);

alert('Youhouu ' + e.localName);
}

似乎不需要添加 pageOffset,因为现在 UIWebView 会自动添加它(我相信来自 iOS 5)。

干杯,

关于javascript - UIWebView、缩放和 elementFromPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14330633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com