- <?xml version="1.0" encoding="utf-8"?>
- <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
- xmlns:s="library://ns.adobe.com/flex/spark"
- xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" width="100%" height="100%">
- <s:layout>
- <s:HorizontalLayout verticalAlign="middle"/>
- </s:layout>
- <fx:Declarations>
- <!-- 将非可视元素(例如服务、值对象)放在此处 -->
- </fx:Declarations>
- <fx:Script>
- <![CDATA[
- import mx.core.DragSource;
- import mx.core.IUIComponent;
- import mx.events.DragEvent;
- import mx.managers.DragManager;
- private static const FORMAT:String = "box";
- private function mouseDownHandle(evt:MouseEvent):void {
- var initiator:IUIComponent = evt.currentTarget as IUIComponent;
- //DragSource 类中包含正被拖动的数据
- var dragSource:DragSource = new DragSource();
- //addData(data:Object, format:String):void向拖动源添加数据和相应的格式 String。
- dragSource.addData(initiator, FORMAT);
- //启动拖放操作。
- //dragInitiator:IUIComponent — 指定启动拖动的组件的 IUIComponent。
- //dragSource:DragSource — 包含正在拖动的数据的 DragSource 对象。
- //mouseEvent:MouseEvent — 包含与启动拖动相关的鼠标信息的 MouseEvent
- DragManager.doDrag(initiator, dragSource, evt);
- }
- private function dragEnterHandle(evt:DragEvent):void {
- //如果数据源中包含请求的格式,则返回 true;否则,返回 false。
- if(evt.dragSource.hasFormat(FORMAT)) {
- DragManager.acceptDragDrop(Canvas(evt.currentTarget));
- }
- }
- private function dropHandle(evt:DragEvent):void {
- //确定拖动后的位置
- var box:Box = Box(evt.dragInitiator);
- box.x = evt.localX;
- box.y = evt.localY;
- }
- ]]>
- </fx:Script>
- <mx:Canvas id="canvas"
- backgroundColor="0xEEEEEE"
- width="80%" height="80%"
- dragEnter="dragEnterHandle(event);"
- dragDrop="dropHandle(event);">
- <mx:Box id="dragItem"
- width="20%" height="20%"
- backgroundColor="0x00FFCC"
- mouseDown="mouseDownHandle(event);" />
- </mx:Canvas>
- </s:Application>