화면 요소를 드래그할 수 있는 draggable 기능은
jquery-ui.js를 사용하면 간단하게 쓸 수 있다!
1. 우선 jquery.js와 jquery-ui.js가 필요하다.
<script src='jquery.js'></script>
<script src='jquery-ui.min.js'></script>
2. 그리고 script에 드래그할 요소를 선언하고 draggable을 써주면 끝!
<script>
$("#toolWrap").draggable();
</script>
3. 추가 작업이 필요하다면 옵션과 이벤트 이용하기
draggable도 다음처럼 여러 옵션과 이벤트가 있는데, 그 중 몇개만 소개해 보겠다.
⭐ 옵션
옵션 | 설명 | 예시 |
handle | 드래그 | handle : '#toolWrapHandle' // #toolWrapHandle 요소를 이용해서 드래그 가능 |
containment | 드래그 이동이 가능한 이동 범위 지정 | containment : '.container' // .container 요소 범위에서만 이동 가능 |
cursor | 드래그하고 있을때 마우스 커서 모양(css)을 바꿔줌 | cursor : 'crosshair' //드래그 할때 커서가 +자 모양으로 바뀜 |
axis | 수평(x)과 수직(y)으로만 움직이고 싶을 때 사용 | axis : "x" //수평(x) 으로만 이동 가능 |
⭐ 이벤트
create | draggable 생성될 때 실행됨 |
start | 드래그가 시작할 때 실행됨 |
drag | 드래그 동안 마우스가 움직일 때 실행됨 |
stop | 드래그를 멈췄을 때 실행됨 |
🍀 옵션과 이벤트 사용
$("#toolWrap").draggable({
handle : '#toolWrapHandle' ,
containment : '.container' ,
cursor : 'crosshair' ,
start : function( event, ui ) {
$("#toolWrapHandle").css("background-color","#216424");
//드래그 하면 핸들의 색상이 바뀜
},
stop : function( event, ui ) {
$("#toolWrapHandle").css("background-color","#4caf50");
//드래그 끝나면 다시 원래 색으로 돌아옴
}
});
#toolWrap이 .container안에서만 이동 가능하고
#toolWrapHandle을 헨들삼아 이동 가능하다.
드래그 할때는 마우스 커서의 모양이 십자모양으로 바뀐다.
이벤트를 사용하여 드래그할때 추가 작업을 할 수 있다.
🍀 전체 코드
<html>
<head>
<meta charset='utf-8'>
<title>EXAMPLE</title>
<link rel='stylesheet' href='jquery-ui.min.css'>
</head>
<style>
.container{background-color:#00c1b045; height:500px; width:500px;margin:100px;}
#toolWrap{background-color:#8bc34a;height: 50px;width: 300px;padding: 20px;}
#toolWrapHandle{background-color: #4caf50;height: 50px;width: 50px;border-radius: 30px;float: right;margin: 0 22px;}
</style>
<body>
<script src='jquery.js'></script>
<script src='jquery-ui.min.js'></script>
<div>
<div class='container'>
container
<div id="toolWrap">
TOOL MENU
<div id="toolWrapHandle">handle</div>
</div>
</div>
</div>
<script>
$("#toolWrap").draggable({
handle : '#toolWrapHandle' ,
containment : '.container' ,
cursor : 'crosshair' ,
start : function( event, ui ) {
$("#toolWrapHandle").css("background-color","#216424");
},
stop : function( event, ui ) {
$("#toolWrapHandle").css("background-color","#4caf50");
}
});
</script>
</body>
</html>
draggable의 옵션과 메서드를 더 알고 싶다면!
draggable API documentation 👇
https://api.jqueryui.com/draggable/
Draggable Widget | jQuery UI API Documentation
Description: Allow elements to be moved using the mouse. Make the selected elements draggable by mouse. If you want not just drag, but drag & drop, see the jQuery UI Droppable plugin, which provides a drop target for draggables. Theming The draggable widge
api.jqueryui.com
'Web > JavaScript' 카테고리의 다른 글
모바일에서 touch-punch 사용시 클릭 이벤트 안되는 오류 개선 (0) | 2022.10.19 |
---|---|
파라미터에 기호 (#,& 등등) 처리 (0) | 2022.06.28 |
Jquery - Set 객체 (0) | 2022.01.28 |
jquery html2canvas - 웹페이지 스크린샷 (0) | 2022.01.07 |
jquery 텍스트에 있는 이모지 제거 (0) | 2021.10.22 |
댓글