将元素移动到手指下,然后使用相同的动作进行拖动

时间:2014-05-14 21:46:30

标签: javascript jquery jquery-ui touch

在touchstart和鼠标按下时,我想将一个元素移动到我的手指或光标下,然后能够拖动它。

JS:

$('.matiMarker').draggable();
$('.matiValMarker').bind("mousedown touchstart",function(e){ 

    var that = this,
    $(this).parent().find('.matiMarker').animate({
        left : $(that).position().left + "px"
    },100);
});

这样会将.matiMarker移动到我的手指/光标下,而我需要发生的是将同一个mousedown / touchstart事件作为拖动的开始。我迷失了如何做到这一点。

1 个答案:

答案 0 :(得分:0)

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Drag your element along mouse click start and end.</title>
<style type="text/css"><!--
#dg {
 width:180px;
 height:100px;
 margin:8px;
 background:#a7daa8;
 cursor:pointer;
}
--></style>
<script type="text/javascript" src="jquery_1.6.1.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.14.js"></script>
<script type="text/javascript"><!--
//This variables stores your element's x and y position.
var xpos; var ypos;
//This method runs when your page is load.
$(document).ready(function() {
  $('#matiMarker').draggable({
    // get the initial X and Y position when dragging starts
    start: function(event, ui) {
      xpos = ui.position.left;
      ypos = ui.position.top;
    },
    // when dragging stops
    stop: function(event, ui) {
      // your draggable element's current position.
      var xmove = ui.position.left;
      var ymove = ui.position.top;
    }
  });
});
--></script>
</head>
<body>
<div id="matiMarker">Click and Drag<br />
Your element which has matiMarker id. </div>
</body>
</html>

通过这种方式,你可以在相同的功能(启动和停止功能)上拖动和移动动作。