技术开发 频道

使用Asp.net2.0和Atlas实现拖放操作


三、动态拖放

既然声明模型比编程模型更简洁,那么你为什么不自己写JavaScript代码来处理Atlas行为呢?如果想动态地加入行为,你可以加入自己的JavaScript代码。声明模型的一个限制是它只能影响在aspx初始化时加入的对象。如果你动态地为aspx页加入对象,那么使用声明模型将无法为这些新加入的对象添加拖动功能。而使用编程模型却可以做到。
为了实现这一功能,我们使用一个可以建立可拖动div对象的方法来替换前面例子中的“pageLoad()”函数。以下的JavaScript函数使用另一个内嵌的div标签建立一个div标签,然后将这个div标签插入到当前页中,最后向这个div标签加入拖动功能。

function createDraggableDiv() { var panel= document.createElement("div"); panel.style.height="100px"; panel.style.width="100px"; panel.style.backgroundColor="Blue"; var panelHandle = document.createElement("div"); panelHandle.style.height="20px"; panelHandle.style.width="auto"; panelHandle.style.backgroundColor="Green"; panel.appendChild(panelHandle); var target = $('containerDiv').appendChild(panel); addFloatingBehavior(panel, panelHandle); }
你只需要在aspx页上放一个按钮,然后在这个按钮中调用“createDraggableDiv()”函数,HTML代码如下:

<input type="button" value="Add Floating Div" onclick="createDraggableDiv();" />
<div id="containerDiv" style="background-color:Purple;height:800px;width:600px;"/>

使用这种方法可以在aspx页中加入许多自己想加入的可拖动控件,因此,一旦你理解并灵活使用Atlas的这些模型,你就可以用事实来证明Atlas的强大和弹性。为了更清楚地说明问题,下面给出了动态拖动的完整代码:
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Imperative Drag and Drop II</title> <script type="text/javascript"> function createDraggableDiv() { var panel= document.createElement("div"); panel.style.height="100px"; panel.style.width="100px"; panel.style.backgroundColor="Blue"; var panelHandle = document.createElement("div"); panelHandle.style.height="20px"; panelHandle.style.width="auto"; panelHandle.style.backgroundColor="Green"; panel.appendChild(panelHandle); var target = $('containerDiv').appendChild(panel); addFloatingBehavior(panel, panelHandle); } function addFloatingBehavior(ctrl, ctrlHandle){ var floatingBehavior = new Sys.UI.FloatingBehavior(); floatingBehavior.set_handle(ctrlHandle); var dragItem = new Sys.UI.Control(ctrl); dragItem.get_behaviors().add(floatingBehavior); floatingBehavior.initialize(); } </script> </head> <body> <form id="form1" runat="server"> <atlas:ScriptManager ID="ScriptManager1" runat="server"> <Scripts> <atlas:ScriptReference ScriptName="AtlasUIDragDrop" /> </Scripts> </atlas:ScriptManager> <h2>Imperative Drag and Drop Code with javascript: demonstrate dynamic loading of behaviors</h2> <input type="button" value="Add Floating Div" onclick="createDraggableDiv();" /> <div id="containerDiv" style="background-color:Purple;height:800px;width:600px;"/> </form> </body> </html>
0
相关文章