FLEX 的元件移動邊界限制
當物件被執行了 startDrag 方法後,他便不受控制愛飛去哪就飛去哪,但是我們必須要決定物件被移動的區域。
這邊用了一個笨方法,來限制物件的移動邊界,如果有更好的方法還請大家提供一下。
當還沒限制邊界的時候點擊物件後移動,黑色的 canvas 是可以被移動到白色的 canvas 之外。
DragTest.mxml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Script>
<![CDATA[
private function mouseDownHandler():void{
this.cv2.startDrag();
}
private function mouseUpHandler():void{
this.cv2.stopDrag();
}
private function moveHandler():void{
trace("aaa");
}
]]>
</mx:Script>
<mx:Canvas id="cv1" width="544" height="324" backgroundColor="#FFFFFF">
<mx:Canvas mouseMove="moveHandler()" id="cv2" x="147" y="46" width="101" height="100" backgroundColor="#000000" buttonMode="true" mouseDown="mouseDownHandler()" mouseUp="mouseUpHandler()">
</mx:Canvas>
</mx:Canvas>
</mx:Application> |
而我們要的目的只可以讓黑色的 canvas 的移動範圍限制在白色的 canvas 裡面,因此我們要加上判斷移動邊界的方法。
DragTest2.mxml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Script>
<![CDATA[
import mx.events.MoveEvent;
private function mouseDownHandler():void{
this.cv2.startDrag();
this.addEventListener(MouseEvent.MOUSE_MOVE,moveHandler);
}
private function mouseUpHandler():void{
this.cv2.stopDrag();
this.removeEventListener(MouseEvent.MOUSE_MOVE,moveHandler);
}
private function moveHandler(event:MouseEvent):void{
if(this.cv2.x <= 0){
this.cv2.x = 0;
this.cv2.stopDrag();
}
if(this.cv2.x >= this.cv1.width - this.cv2.width){
this.cv2.x = this.cv1.width - this.cv2.width;
this.cv2.stopDrag();
}
if(this.cv2.y <= 0){
this.cv2.y = 0;
this.cv2.stopDrag();
}
if(this.cv2.y >= this.cv1.height - this.cv2.height){
this.cv2.y = this.cv1.height - this.cv2.height;
this.cv2.stopDrag();
}
}
]]>
</mx:Script>
<mx:Canvas id="cv1" width="544" height="324" backgroundColor="#FFFFFF">
<mx:Canvas id="cv2" x="147" y="46" width="101" height="100" backgroundColor="#000000" buttonMode="true" mouseDown="mouseDownHandler()" mouseUp="mouseUpHandler()">
</mx:Canvas>
</mx:Canvas>
</mx:Application> |
不過這個方法還是有點小問題啦,如果有更正式的做法請告訴我吧,謝謝。
Random Posts
Loading…
相關文章 :










这样可完美解决,一点不会溢出.
但是鼠标移出容器后,没有启动stopDrag()。这样就造成了鼠标移出容器后,当鼠标重新回到容器内,会带着拖动的子项随便跑。除非单击一下才会stopDrag()。需要监听鼠标从子项移出事件并妥善处理,方可真正完美实现。
this.容器.addEventListener(MouseEvent.MOUSE_OUT, function(e:*):void{ newEC.stopDrag(); });为了解决鼠标移出容器后弹起鼠标,鼠标弹起事件的失效(出现上述问题),加入了这段代码。
当鼠标移出容器后,自动stopDrag(). 但是这样一来,拖动子项的时候,子元件会抖动,而且拖动过快,就会立即stopDrag(),原因不明。
觉得,既然还不如第一个效果好,就让用户接受第一种效果吧,习惯了就好了:P
@勇智
一件事情方法有很多種
只要看能不能解決需求
很謝謝您的分享
我也因此學到了一些東西喔!!~^^