下面我们开始分解操作:
辅助js库文件:
/*
bwH5.js by Bill Weinman
<http://bw.org/contact/>
created 2011-04-16
updated 2011-07-07
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
*/
var _bwH5_version = "1.1.3";
// useful for finding elements
var element = function(id) { return document.getElementById(id); }
var errorMessage = undefined;
var elStatus;
function getOpenDatabase() {
try {
if( !! window.openDatabase ) return window.openDatabase;
else return undefined;
} catch(e) {
return undefined;
}
}
function getLocalStorage() {
try {
if( !! window.localStorage ) return window.localStorage;
else return undefined;
} catch(e) {
return undefined;
}
}
function getSessionStorage() {
try {
if( !! window.sessionStorage ) return window.sessionStorage;
else return undefined;
} catch(e) {
return undefined;
}
}
function dispError( message ) {
errorMessage = '<p class="error">' + message + '</p>';
haveError = true;
}
function statusMessage(s) {
if(!elStatus) elStatus = element('statusMessage');
if(!elStatus) return;
if(s) elStatus.innerHTML = s;
else elStatus.innerHTML = ' ';
}
function bwTable( wrap ) {
this.wrap = ( wrap == undefined ) ? true : wrap; // default to true
this.rows = new Array();
this.header = [];
this.setHeader = function( row ) {
this.header = row;
}
this.addRow = function( row ) {
this.rows.push(row);
}
this.updateRow = function( index, row ) {
this.rows[index] = row;
}
this.getRow = function ( index ) {
return this.rows[index];
}
this.countRows = function () {
return this.rows.length;
}
this.getTableHTML = function () {
var a = '';
if(this.wrap) a += '<table class="bwTable">\n';
a += this.getHeaderHTML();
for(var row in this.rows) {
a += this.getRowHTML(this.rows[row]);
}
if(this.wrap) a += '</table>\n';
return a;
}
this.getHeaderHTML = function () {
if( this.header.length == 0 ) return '';
var a = '<tr>';
for( var cell in this.header ) {
a += '<th>' + this.header[cell] + '</th>';
}
a += '</tr>\n';
return a;
}
this.getRowHTML = function (row ) {
var a = '<tr>';
for( var cell in row ) {
var v= row[cell];
if(v == null) v = '<span class="red">NULL</span>';
a += '<td>' + v + '</td>';
}
a += '</tr>\n';
return a;
}
this.writeTable = function () {
document.write(this.getTableHTML());
}
}
辅助的css文件:
/*
main.css by Bill Weinman
<http://bw.org/contact/>
created 2011-04-16
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
v 1.0.1 - bw 2011-04-19
*/
/* -------- color guide (From Explore California) ----------
#3c6b92 : main blue
#6acce2 : light blue
#2c566a : teal accent
#193742 : dark blue
#e1d8b9 : sand accent
#cb7d20 : orange accent
#51341a : brown
#995522 : dark orange (used for links or high contrast accents)
#cb202a : red accent (this color does not encode well, use only for small accents)
#896287 : purple
*/
/* reasonable reset */
html, body, div, section, article, aside, header, hgroup, footer, nav, h1, h2, h3, h4, h5, h6, table, tr, td,
p, blockquote, address, time, span, em, strong, img, ol, ul, li, dl, dt, figure, canvas, video {
margin: 0;
padding: 0;
border: 0;
}
body {
font-family: Georgia, serif; /* default page font */
background-color: #3c6b92;
}
.red {
color: #cb202a;
}
p.message, p.error {
font: normal 1em Helvetica, Arial, sans-serif;
padding: 0 3px;
}
p.message {
border: 1px solid #995522;
background-color: #e1d8b9;
color: black;
}
p.error {
border: 1px solid #193742;
background-color: #cb202a;
color: white;
}
#content {
width: 85%;
margin: 20px auto;
padding: 5px;
background-color: white;
min-height: 300px;
}
#content h1, #content h2 {
font: normal 1.4em Helvetica, Arial, sans-serif;
color: #3c6b92;
}
#content p, h1, h2, h3 {
margin-bottom: .5em;
}
#content h1 {
border-bottom: solid 2px #3c6b92;
}
#content h2.error {
color: #cb7d20;
}
/* bwTable */
.bwTable {
background: #c3cebc;
margin-bottom: .5em;
border: 1px solid #995522;
border-collapse: collapse;
}
.bwTable tr, .bwTable td, .bwTable th {
font: normal 1em Helvetica, Arial, sans-serif;
text-align: left;
border: solid 1px #995522;
padding: 1px 3px;
}
.bwTable tr:nth-child(odd) {
background: #e1d8b9;
}
.bwTable th {
background: #193742;
color: #c3cebc;
border: solid 1px #51341a;
}
.bwTable td {
min-width: 100px;
}
/* form */
#form {
margin-bottom: 10px;
border-bottom: 2px solid #3c6b92;
}
#form input[type=text] {
width: 300px;
}
#form td.button, #form td.label {
text-align: right;
}
#form td.label {
padding-right: 3px;
}
1)判断浏览器是否支持drag & drop操作:
<!DOCTYPE html>
<html>
<!--
detecting.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-12
updated 2011-07-17
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
HTML5 Drag and Drop
</title>
<link rel="stylesheet" type="text/css" href="../CSS/main.css" />
<script type="text/javascript" src="../Javascript/bwH5.js"></script>
<script type="text/javascript">
var dndSupported; // true if drag and drop supported
function detectDragAndDrop() {
if (navigator.appName == 'Microsoft Internet Explorer') {
// IE浏览器
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
var rv = parseFloat( RegExp.$1 );
// IE6以上支持
if(rv >= 6.0) return true;
}
return false;
}
// 其余浏览器在页面中创建一个span对象看是否支持draggable属性
if ('draggable' in document.createElement('span')) return true;
return false;
}
function init() {
if((dndSupported = detectDragAndDrop())) {
statusMessage('Using HTML5 Drag and Drop');
} else {
statusMessage('This browser does not support Drag and Drop');
}
}
window.onload = function() {
init();
}
</script>
</head>
<body>
<div id="content">
<h1>
HTML5 Drag and Drop
</h1>
<p class="message" id="statusMessage" />
</div>
</body>
</html>
2)对一个简单的事件编程,这里选择开始拖拽事件
<!DOCTYPE html>
<html>
<!--
listening.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-12
updated 2011-07-17
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
HTML5 Drag and Drop
</title>
<link rel="stylesheet" type="text/css" href="../CSS/main.css" />
<link rel="stylesheet" type="text/css" href="../CSS/rps.css" />
<script type="text/javascript" src="../Javascript/bwH5.js"></script>
<script type="text/javascript">
var dndSupported; // true if drag and drop supported
function detectDragAndDrop() {
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
var rv = parseFloat( RegExp.$1 );
if(rv >= 6.0) return true;
}
return false;
}
if ('draggable' in document.createElement('span')) return true;
return false;
}
function handleDragStart(event) {
statusMessage('drag started');
}
function init() {
if((dndSupported = detectDragAndDrop())) {
statusMessage('Using HTML5 Drag and Drop');
// 注册事件响应函数
// window.addEventListener
// 方法原型
// public override function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
// 参数:
// type:String,事件的类型。
// listener:Function, 事件处理函数
// useCapture:Boolean (default = false), 侦听器在侦听时有三个阶段:捕获阶段、目标阶段和冒泡阶段。顺序 为:捕获阶段(根节点到子节点检查是否调用了监听函数)→目标阶段(目标本身)→冒泡阶段(目标本身到根节点)。
// 此处的参数确定侦听器是运行于捕获阶段、 目标阶段还是冒泡阶段。
// 如果将 useCapture 设置为 true,则侦听器只在捕获阶段处理事件,而不在目标或冒泡阶段处理事件。
// 如果useCapture 为 false,则侦听器只在目标或冒泡阶段处理事件。
// 要在所有三个阶段都侦听事件,请调用两次 addEventListener,一次将 useCapture 设置为 true,第二次再将useCapture 设置为 false。
element('img1').addEventListener('dragstart', handleDragStart, false);
} else {
statusMessage('This browser does not support Drag and Drop');
}
}
window.onload = function() {
init();
}
</script>
</head>
<body>
<div id="content">
<h1>
HTML5 Drag and Drop
</h1>
<p class="message" id="statusMessage" />
<div id="columns">
<!-- draggable属性决定是否能够拖动 -->
<div class="rps"><img id="img1" src="../Images/Rock.png" draggable="true" /><footer>Rock</Footer></div>
<div class="rps" id="dz1"><img draggable="false" src="../Images/DropZone.png" /><footer>Drop Here</Footer></div>
</div>
<p id="clear" /> <!-- provide some space at the bottom -->
</div>
</body>
</html>
3)两个对象的交互处理,一个drag,一个drop
<!DOCTYPE html>
<html>
<!--
events.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-12
updated 2011-07-17
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
HTML5 Drag and Drop
</title>
<link rel="stylesheet" type="text/css" href="../CSS/main.css" />
<link rel="stylesheet" type="text/css" href="../CSS/rps.css" />
<script type="text/javascript" src="../Javascript/bwH5.js"></script>
<script type="text/javascript">
var dndSupported; // true if drag and drop supported
function detectDragAndDrop() {
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
var rv = parseFloat( RegExp.$1 );
if(rv >= 6.0) return true;
}
return false;
}
if ('draggable' in document.createElement('span')) return true;
return false;
}
function handleDragStart(event) {
statusMessage('drag started');
}
var eventCounter = 1;
function handleDragEvent(e) {
if(e.preventDefault) e.preventDefault();
statusMessage('count: ' + eventCounter++);
}
function handleDragOver(e) {
if(e.preventDefault) e.preventDefault();
return false; // some browsers may need this to prevent default action
}
function init() {
if((dndSupported = detectDragAndDrop())) {
statusMessage('Using HTML5 Drag and Drop');
// 注册拖拽对象
element('img1').addEventListener('dragstart', handleDragStart, false);
// 组织浏览器默认事件响应
element('dz1').addEventListener('dragover', handleDragOver, false);
// 注册停泊对象
element('dz1').addEventListener('drop', handleDragEvent, false);
} else {
statusMessage('This browser does not support Drag and Drop');
}
}
window.onload = function() {
init();
}
</script>
</head>
<body>
<div id="content">
<h1>
HTML5 Drag and Drop
</h1>
<p class="message" id="statusMessage" />
<div id="columns">
<div class="rps"><img id="img1" src="../Images/Rock.png" draggable="true" /><footer>Rock</Footer></div>
<div class="rps" id="dz1"><img draggable="false" src="../Images/DropZone.png" /><footer>Drop Here</Footer></div>
</div>
<p id="clear" /> <!-- provide some space at the bottom -->
</div>
</body>
</html>
4)使用一个drop zone,以及在开始drag和drop之后分别设置和获取数据
<!DOCTYPE html>
<html>
<!--
dropzone.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-12
updated 2011-07-17
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
HTML5 Drag and Drop
</title>
<link rel="stylesheet" type="text/css" href="../CSS/main.css" />
<link rel="stylesheet" type="text/css" href="../CSS/rps.css" />
<script type="text/javascript" src="../Javascript/bwH5.js"></script>
<script type="text/javascript">
var dndSupported; // true if drag and drop supported
var DNDType = 'text/plain'; // used to identify a particular drop
function detectDragAndDrop() {
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
var rv = parseFloat( RegExp.$1 );
if(rv >= 6.0) return true;
}
return false;
}
if ('draggable' in document.createElement('span')) return true;
return false;
}
function handleDragStart(event) {
// 设置数据
statusMessage('drag started (' + event.target.dataset.value + ')');
// 注意这里的effectAllowed和dz1中的dropzone要一致,表示拖拽过程中的鼠标效果
event.dataTransfer.effectAllowed = 'move'; // copy, move, or link
event.dataTransfer.setData(DNDType, event.target.dataset.value);
}
function handleDrop(event) {
if(event.preventDefault) event.preventDefault();
// 获取数据
var data = event.dataTransfer.getData(DNDType);
statusMessage('received drop: ' + data);
}
function handleDragOver(event) {
if(event.preventDefault) event.preventDefault();
return false; // some browsers may need this to prevent default action
}
function init() {
if((dndSupported = detectDragAndDrop())) {
statusMessage('Using HTML5 Drag and Drop');
element('img1').addEventListener('dragstart', handleDragStart, false);
element('dz1').addEventListener('dragover', handleDragOver, false);
element('dz1').addEventListener('drop', handleDrop, false);
} else {
statusMessage('This browser does not support Drag and Drop');
}
}
window.onload = function() {
init();
}
</script>
</head>
<body>
<div id="content">
<h1>
HTML5 Drag and Drop
</h1>
<p class="message" id="statusMessage" />
<div id="columns">
<div class="rps"><img id="img1" src="../Images/Rock.png" draggable="true" data-value="I Am a Rock" /><footer>Rock</Footer></div>
<!-- dropzone 指定当拖拽数据放开的时候会发生什么copy|move|link -->
<div class="rps" id="dz1" dropzone="move s:text/plain"><img src="../Images/DropZone.png" /><footer>Drop Here</Footer></div>
</div>
<p id="clear" /> <!-- provide some space at the bottom -->
</div>
</body>
</html>
5)使用全局变量
<!DOCTYPE html>
<html>
<!--
nodropzone.html by Bill Weinman
<http://bw.org/contact/>
created 2011-07-12
updated 2011-07-17
Copyright (c) 2011 The BearHeart Group, LLC
This file may be used for personal educational purposes as needed.
Use for other purposes is granted provided that this notice is
retained and any changes made are clearly indicated as such.
-->
<head>
<title>
HTML5 Drag and Drop
</title>
<link rel="stylesheet" type="text/css" href="../CSS/main.css" />
<link rel="stylesheet" type="text/css" href="../CSS/rps.css" />
<script type="text/javascript" src="../Javascript/bwH5.js"></script>
<script type="text/javascript">
var dndSupported; // true if drag and drop supported
var sourceID;
var payloads = {
img1: "I Am a Rock",
img2: "I Am Paper",
img3: "I Am Scissors"
};
function detectDragAndDrop() {
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
var rv = parseFloat( RegExp.$1 );
if(rv >= 6.0) return true;
}
return false;
}
if ('draggable' in document.createElement('span')) return true;
return false;
}
function handleDragStart(event) {
// 得到事件发生的对象id
sourceID = this.id;
statusMessage('drag started (' + payloads[sourceID] + ')');
}
function handleDrop(event) {
if(event.preventDefault) event.preventDefault();
// 这里获取保存的数据
statusMessage('received drop: ' + payloads[sourceID]);
}
function handleDragOver(event) {
if(event.preventDefault) event.preventDefault();
return false; // some browsers may need this to prevent default action
}
function init() {
if((dndSupported = detectDragAndDrop())) {
statusMessage('Using HTML5 Drag and Drop');
element('img1').addEventListener('dragstart', handleDragStart, false);
element('dz1').addEventListener('dragover', handleDragOver, false);
element('dz1').addEventListener('drop', handleDrop, false);
} else {
statusMessage('This browser does not support Drag and Drop');
}
}
window.onload = function() {
init();
}
</script>
</head>
<body>
<div id="content">
<h1>
HTML5 Drag and Drop
</h1>
<p class="message" id="statusMessage" />
<div id="columns">
<div class="rps"><img id="img1" src="../Images/Rock.png" draggable="true" /><footer>Rock</Footer></div>
<div class="rps" id="dz1" ><img src="../Images/DropZone.png" /><footer>Drop Here</Footer></div>
</div>
<p id="clear" /> <!-- provide some space at the bottom -->
</div>
</body>
</html>