我这里有一个代码,它使用jquery和jquery UI中的可拖动。
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script src="js/jquery-ui.js"></script>
<style>
#draggable, #draggable2, #draggable3 {border: 0px solid black; background-color : transparent; width: 150px; height: 150px; padding: 0.5em; }
</style>
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#draggable2" ).draggable();
$( "#draggable3" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">Test1</div>
<div id="draggable2" class="ui-widget-content">Test2</div>
<div id="draggable3" class="ui-widget-content">Test3</div>
</body>
</html>
我需要为每个元素获取位置corrdinates x和y。我找不到如何获得这些。 另外如何限制可拖动的地方。我的意思是如何创建边框,这些对象只能在此边框内移动。
答案 0 :(得分:4)
你想要这个??
$("#draggable").draggable({
start: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#start").html(" x: " + relX + ", y: " + relY);
},
stop: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#end").html(" x: " + relX + ", y: " + relY);
},
drag: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#current").html(" x: " + relX + ", y: " + relY);
}
});
此代码将在拖动时获取坐标