Dojo之路:如何利用Dojo实现Drag and Drop效果


如今各种使用AJAX技术的站点都实现了Drag and Drop(拖动)效果,利用Dojo框架也可以很方便的实现,相比较其它框架,代码更少,且对浏览器的兼容性支持比较好。

  先看一下效果,以下是51AJAX.com站点首页的效果,其中各个模块是可以任意拖动的:
  screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" onclick="if(!this.resized) {return true;} else {window.open('/upload/200741022625273.jpg');}" alt="" src="/upload/200741022625273.jpg" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" border=0>

  如何来实现呢?以下是具体步骤。为简单起见,做了一个Drag and Drop的Demo页面:

  screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" onclick="if(!this.resized) {return true;} else {window.open('/upload/200741022628497.jpg');}" alt="" src="/upload/200741022628497.jpg" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" border=0>
  以下是具体步骤:
  1.html部分
  要实现拖动,首先要有容器,其次要有可拖动的元素。在这里我们设置了三个Div作为容器,ID分别是container1,container2,container3,每个容器中各放置了一个Div作为可拖动元素,它们的class是divdrag。
  2.javascript代码  
  首先在头部加入对dojo.js的引用,然后根据获取class为divdrag的元素,把它们注册为dojo.dnd.HtmlDragSource对象,再将container1,container2,container3注册为三个容器,且指定容器中的可拖动元素可以被拖动到的容器,以上事件封装成一个函数,增加至window.onload事件中。

要下载完整的Dojo框架,请点击这里下载:http://download.dojotoolkit.org/release-0.3.1/dojo-0.3.1-ajax.zip
复制代码 代码如下:

//引用以下两个dojo包
dojo.require("dojo.style");
dojo.require("dojo.dnd.*");

function init(){
//利用classname取到元素列表,将其注册为dojo.dnd.HtmlDragSour
var arr=dojo.html.getElementsByClass('divdrag')
for(var i=0;i<arr.length;i++){
var parentDiv=arr[i].parentNode.id
new dojo.dnd.HtmlDragSource(arr[i],parentDiv);
}
//定义容器
new dojo.dnd.HtmlDropTarget("container1", ["container1","container2","container3"]);
new dojo.dnd.HtmlDropTarget("container2", ["container1","container2","container3"]);
new dojo.dnd.HtmlDropTarget("container3", ["container1","container2","container3"]);
}

//增加到window.onload事件中
window.onload=function(){init();}

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3