Skip to content

Instantly share code, notes, and snippets.

@Rachel0211
Created April 12, 2016 10:15
Show Gist options
  • Select an option

  • Save Rachel0211/e56ad63e0cea775e1be660e76b8f1ee6 to your computer and use it in GitHub Desktop.

Select an option

Save Rachel0211/e56ad63e0cea775e1be660e76b8f1ee6 to your computer and use it in GitHub Desktop.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>미션</title>
<style>
* {
margin:0;
padding:0;
}
.wrap {
margin:50px;
}
.select {
width:800px;
height:100px;
border:1px solid #000;
}
.select img {
width:150px;
float:left;
}
.container {
position: absolute;
width:800px;
height:400px;
border:1px solid #000;
}
.container img {
position: absolute;
width:100px;
}
</style>
<script type="text/javascript" src="../../../libs/jquery-1.11.0.min.js"> </script>
<script>
/*
미션03: 드래그앤드 드롭만들기
요구사항에 맞게 드래그앤드 드롭 기능을 만들어 주세요.
요구사항 분석
1. 초기 시작 시 컨테이너(.container) 영역의 이미지는 랜덤하게 출력되어야 합니다. 단, 컨테이너 영역을 벗어나면 안 됩니다.
2. 컨테이너 영역의 이미지를 드래그되게 만들어 주세요.
3. 드래그 이미지를 선택 영역에 드롭하는 경우 해당 이미지를 선택 영역으로 이동시켜 주세요.
*/
/*
* step #00
* - 기본 레이아웃 잡기
*/
$(document).ready(function(){
var $image = init();
setRandomPosition($image);
initEvent($image);
})
function init(){
return $('.container img');
}
function initEvent($image){
var zindex = 0;
var drag = false;
var $target = null;
var startPos = {
x : 0,
y : 0
}
$image.on('mousedown', function(e){
console.log("mousedown");
drag = true;
$target = $(this);
var offset = $target.offset();
startPos.x = e.pageX - offset.left;
startPos.y = e.pageY - offset.top;
zindex ++;
$target.css({
"z-index" : zindex
});
dragEvent(drag, $target, startPos);
});
}
function dragEvent(drag, $target, startPos){
$(document).on('mousemove', function(e){
if(drag){
e.preventDefault();
//debugger;
console.log("mousemove");
$target.offset({
left : e.pageX - startPos.x,
top : e.pageY - startPos.y
});
}
})
.on('mouseup', function(e){
console.log("mouseup");
drag = false;
$target = null;
//$(document).off();
});
}
function setRandomPosition($image){
var size = {
width : $image.first().height(),
height : $image.first().width()
};
$image.each(function(){
//debugger;
var cont = $('.container'),
height = cont.height()-size.height
width = cont.width()-size.width;
var x = Math.floor(Math.random()*width),
y = Math.floor(Math.random()*height);
$(this).css({
left : x,
top : y
})
});
}
</script>
</head>
<body>
<div class="wrap">
<div class="select">
<!-- 여기에 이미지를 드래그&드랍 하면 추가 됩니다. -->
</div>
<div class="container">
<img src="banners/1.png" >
<img src="banners/2.png" >
<img src="banners/3.png" >
<img src="banners/4.png" >
<img src="banners/5.png" >
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment