拖曳貼齊 - jQuery UI draggable Options snap

拖曳貼齊可以拖曳的元素和其它元素在接近時自動貼齊

使用方法可用snap:true
$("#eleID").draggable({ snap: true  });
或是用選擇器指定要貼齊的對象
$("#eleID").draggable({ snap: "#drag1"});

以下有2個範例,一個是使用snap:true,另一個是用選擇器設定貼齊的對象,試著拖曳以下範例中的方框並接近
其它方框

相關參數
snap modesnap tolerance
範例jQuery UI 拖曳貼齊
範例程式碼 Expand
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://www.pureexample.com/js/lib/jquery.ui.touch-punch.min.js"></script>


<!-- CSS -->
<style type="text/css">
.drag {
    width: 100px;
    height: 100px;
    line-height: 100px;
    border: 1px solid black;
    cursor: pointer;
    border-radius: 10px;
    text-align: center;
    background-color: lightpink;
}

.container {
    background-color: lightblue;
    width: 300px;
    height: 400px;
    border: 1px solid black;
    float: left;
    margin-right: 30px;
}
</style>


<!-- Javascript -->
<script>
$(function () {        
	$("#drag1").draggable({
		containment: "#c1",
		stack: ".drag",
		snap: true        
	});

	$("#drag2").draggable({
		containment: "#c1",
		stack: ".drag",
		snap: false        
	});

	$("#drag3").draggable({
		containment: "#c2",
		stack: ".drag",
		snap: "#drag4"        
	});

	$("#drag5").draggable({
		containment: "#c2",
		stack: ".drag",
		snap: "#drag6"        
	});    
});
</script>

<!-- HTML -->
<div id="c1" class="container">
    <div style="text-align:center"></div>
    <div id="drag1" class="drag">可貼齊</div>
    <div id="drag2" class="drag" style="background-color:lightgray">不可貼齊</div>
</div>
<div id="c2" class="container">
    <div style="text-align:center">用選擇器設定貼齊效果</div>
	<div id="drag3" class="drag" style="position:relative;left:20px;float:left">可與1貼齊</div>
    <div id="drag4" class="drag" style="position:relative;left:30px;float:left;background-color:lightgray;border:1px dotted black;z-index:1">1</div>
    <div id="drag5" class="drag" style="position:relative;left:20px;top:150px;float:left">可與2貼齊</div>
    <div id="drag6" class="drag" style="position:relative;left:30px;top:150px;float:left;background-color:lightgray;border:1px dotted black">2</div>
</div>


comments powered by Disqus