想讓網頁上的元素能被使用者拖著跑?借助 jQuery UI 的 draggable 功能,只要一行程式碼就能實現。以下分四個步驟說明。
<script src="https://code.jquery.com/jquery-1.9.1.js"></script> <script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<div id="draggable"> <p>Drag me around!</p> </div>
#draggable {
width:150px;
height:150px;
padding:0.5em;
border:1px solid;
}
<script>
$(function() {
$('#draggable').draggable();
});
</script>
<!-- import the necessary files -->
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$('#draggable').draggable();
});
</script>
<style>
#draggable {
width:150px;
height:150px;
padding:0.5em;
border:1px solid;
}
</style>
<div id="draggable">
<p>Drag me around!</p>
</div>
核心其實就是 $('#draggable').draggable(); 這一行。只要引入 jQuery 與 jQuery UI,再對目標元素呼叫 draggable() 方法,元素立刻就能被拖動,非常適合製作可拖曳的浮動視窗、小工具等互動元件。