Skip to content

Instantly share code, notes, and snippets.

@tango238
Created August 25, 2011 02:06
Show Gist options
  • Save tango238/1169797 to your computer and use it in GitHub Desktop.
Save tango238/1169797 to your computer and use it in GitHub Desktop.
[HTML5]Drag&Drop
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>Drag & Drop</title>
<body>
<section id="wrapper">
<header>
<h1>Drag & Drop</h1>
</header>
<style>
#holder {
border: 5px dashed #ccc;
width : 450px;
height: 450px;
margin: 20px auto;
}
#holder.hover {
border: 5px dashed #f33;
}
p.success {
background-color: #0f0;
}
p.fail {
background-color: #f00;
}
</style>
<article>
<div id="holder"></div>
<p id="status">Not Supported</p>
</article>
<script>
(function(){
var holder = document.getElementById('holder');
var status = document.getElementById('status');
// ブラウザがAPIをサポートしているか
if (typeof window.FileReader === 'undefined') {
status.className = 'fail';
} else {
status.className = 'success';
status.innerHTML = 'File API & FileReader available';
}
// ドラッグ中に holder の上にマウスが来たとき
holder.ondragover = function(){
this.className = 'hover';
return false;
};
// ドラッグが終わったとき
holder.ondragend = function (){
this.className = '';
return false;
};
// ドロップされたとき
holder.ondrop = function (e) {
// クラス名を空白にする
this.className = '';
// ファイルを取得する
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.onload = function (event) {
// holder の背景にドロップされた画像をセットする
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
// ファイルを読み込む(読み込みが完了したら onload が実行される)
reader.readAsDataURL(file);
return false;
};
})();
</script>
</section>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment