所以我有一个UIWebView,我在其中添加了一个触摸手势,我想找到在Web视图中点击的图像的x,y原点坐标,或者如果可能的话,在xy坐标中找到图像的中心网络视图。我的代码是:
- (CGPoint) topLeftPointsForImage:(UIGestureRecognizer *)sender
{
CGPoint pt = [sender locationInView:self];
NSString * offsetTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetTop", pt.x, pt.y
];
NSString * offsetLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).offsetLeft", pt.x, pt.y
];
NSString * scrollTop = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollTop", pt.x, pt.y
];
NSString * scrollLeft = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).parentNode.scrollLeft", pt.x, pt.y
];
float x = [[self stringByEvaluatingJavaScriptFromString:offsetTop] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollTop] floatValue];
float y = [[self stringByEvaluatingJavaScriptFromString:offsetLeft] floatValue] - [[self stringByEvaluatingJavaScriptFromString:scrollLeft] floatValue];
NSLog(@"Coor height is %f with coor width is %f", x, y);
CGPoint point = CGPointMake(x, y);
return point;
}
然而,这似乎并没有给我一个正确的价值。我不是一个javascript大师,所以寻找一些建议。
答案 0 :(得分:1)
如果您在html页面中使用jQuery,那么您可以尝试使用:
NSString * offsetTop = [NSString stringWithFormat:@"$(document).elementFromPoint(%f, %f).offsetTop;", pt.x, pt.y
];
还要注意声明末尾的分号。所有Javascript语句必须有效且正确终止,就像在html页面内一样。
如果要注入库,则必须正确放入带有名称空间的函数类,如下所示:
"(function () {return "your data";}) ();"