在 JavaScript 中,我们有 document.elementfrompoint 来获取基于坐标的元素。在 Openlaszlo 中是否有类似的东西可以根据坐标获取视图?
2 回答
OpenLaszlo 中没有直接支持该功能,但对于基于 ActionScript 3 的运行时,您可以使用flash.display.DisplayObjectContainer#getObjectsUnderPoint()方法。在 DHTML 运行时,您可以使用document.elementFromPoint(x, y),并且基于所有现代浏览器都应该支持的 Quirksmode。
这是一个实现方法的示例程序canvas.elementFromPoint()
:
<canvas debug="true">
<passthrough when="$as3">
import flash.geom.Point;
</passthrough>
<view id="background" width="100%" height="100%" bgcolor="#eeeeee" clickable="true"/>
<view id="red" x="200" y="100" width="200" height="200" bgcolor="#ff0000" opacity="0.3" clickable="true" />
<view id="green" x="150" y="200" width="200" height="200" bgcolor="#00ff00" opacity="0.3" clickable="true"/>
<view id="blue" x="250" y="200" width="200" height="200" bgcolor="#0000ff" opacity="0.3" clickable="true"/>
<handler name="onclick" reference="lz.GlobalMouse">
canvas.elementFromPoint();
</handler>
<method name="elementFromPoint"><![CDATA[
var mouseX = canvas.getMouse('x'),
mouseY = canvas.getMouse('y'),
objects = null, // array of objects at mouse pointer in SWF runtime
element = null; // The element we are looking for
Debug.info( 'mouse position: x=' + mouseX + ' / mouseY=' + mouseY );
if ($as3) {
// in SWF runtime, use the DisplayObjectContainer.getObjectsUnderPoint() method
objects = canvas.getDisplayObject().getObjectsUnderPoint(new Point(mouseX, mouseY));
element = objects[objects.length-1].owner;
} else {
// in DHTML, we can use elementFromPoint, and need to retrieve the owner view of the div
element = document.elementFromPoint(mouseX, mouseY).owner.owner;
}
Debug.info('View under mousecursor:', element);
return element;
]]></method>
</canvas>
有 4 个视图,一个背景视图缩放为 100% x 100%。以及三种颜色视图:红色、绿色和蓝色 - 蓝色是最上面的一种。单击视图时,将返回正确的视图对象。
该代码已在 Chrome 22.0、Firefox 16.0.1 和 Opera 12.02 的 DHTML 运行时中进行了测试。Flash 应该适用于所有浏览器,我没有用 IE 测试过。
我不这么认为。您必须构建自己的自定义数组或观察者对象,收集所有视图,然后遍历所有项目并检查坐标是否在视图的边界框内。在 Flash 中也有类似“hitTest”的东西,它可能类似于 JavaScript 的“document.elementfrompoint”来获得精确的像素匹配,以防边界框对你来说不够用。
塞巴斯蒂安