CJuiDraggable 封裝 jQuery UI Draggable,將包裹區域內的任意內容(圖片、表單、Widget)變為可拖曳。
<?php $this->beginWidget('zii.widgets.jui.CJuiDraggable', array(
'options' => array(
'cursor' => 'move', // 拖曳時游標
'revert' => false, // 放開後是否回彈
'opacity' => 0.7, // 拖曳時透明度
'zIndex' => 1000, // 拖曳時層級
'containment' => 'parent', // 限制拖曳範圍:parent/document/window/selector
'scroll' => true, // 自動捲動容器
),
'htmlOptions' => array(
'style' => 'width:200px; height:200px; padding:5px; border:1px solid #ddd; background:#f9f9f9;',
),
)); ?>
<img id="image" width="200" src="/images/draggable-demo.png" alt="可拖曳圖片">
<?php $this->endWidget(); ?>
| 選項 | 說明 | 常用值 |
|---|---|---|
handle | 指定拖曳把手(CSS 選擇器) | '.drag-handle', 'h3' |
cancel | 禁止拖曳的子元素 | 'input,button,a' |
containment | 限制拖曳邊界 | 'parent', 'document', '#container', [x1,y1,x2,y2] |
grid | 網格對齊步長 | [50, 50] |
snap | 吸附目標 | true, '.snap-target' |
axis | 限制軸向 | 'x', 'y' |
distance | 啟動拖曳最小距離 | 10 (px) |
delay | 啟動延遲 | 200 (ms) |
<?php $this->beginWidget('zii.widgets.jui.CJuiDraggable', array(
'options' => array(
'handle' => '.panel-header', // 只有標題列可拖曳
'cancel' => 'input,textarea,button,select,a', // 表單元素不可拖曳
'containment' => '#dashboard',
),
'htmlOptions' => array('class' => 'dashboard-widget'),
)); ?>
<div class="panel-header"><h3>可拖曳面板</h3></div>
<div class="panel-body">
<input type="text" placeholder="此輸入框不會觸發拖曳">
</div>
<?php $this->endWidget(); ?>
'options' => array(
'start' => 'js:function(event, ui) { $(this).addClass("dragging"); }',
'drag' => 'js:function(event, ui) { console.log(ui.position); }',
'stop' => 'js:function(event, ui) {
$(this).removeClass("dragging");
$.post("savePosition", { x: ui.position.left, y: ui.position.top });
}',
),
參考下一章 CJuiDroppable,可建立「拖曳來源」與「放置目標」的完整互動。
position: relative/absolute/fixed 才能正確定位distance/delay 減少誤觸發