这个
demo显示了在使用jQuery拖动组件时如何发送事件.我在DIV中有一个组件,当我拖动该组件时,我想打印出相对于DIV容器的组件坐标,任何jQuery pro都可以帮助我.这是我到目前为止所得到的.
<div id="container" style="width: 400px; height: 4000px; border: 1px solid black;" >
<div id="draggable" style="width: 150px; height: 150px; background-color: black; cursor: move;">
<div class="count"/>
</div>
</div>
<script>
jQuery(function(){
jQuery("#draggable").draggable({
containment: "#contain",scroll: false,drag: function(){
}
});
function updateCoordinate(newCoordinate){
jQuery(".count").text(newCoordinate);
}
});
</script>
在拖动的回调事件中,我需要弄清楚pageX,pageY以及offsetX,offsetY以找出拖动时组件的相对位置.我是jQuery的新手.我知道我可以像这样获得pageX,pageY和offsetX,offsetY
jQuery("#container").click(function(event){
var offset = jQuery(this).offset();
var pageX = event.pageX;
var pageY = event.pageY;
});
但我不确定如何将它们组合在一起.
解决方法
像这样?
http://jsfiddle.net/aasFx/36/
$(function() {
$("#draggable").draggable({
containment: "#contain",drag: function() {
var $this = $(this);
var thisPos = $this.position();
var parentPos = $this.parent().position();
var x = thisPos.left - parentPos.left;
var y = thisPos.top - parentPos.top;
$this.text(x + "," + y);
}
});
});