1

嗨,我试图创建一个可拖动的对象,我有一些作品,但是鼠标一直捕捉到对象的中心,我该如何解决这个问题。这是我的例子。我希望鼠标停留在用户单击对象的位置

<html>
  <head>
    <script type="text/javascript" src="javascript/jquery-1.8.2.min.js"></script>
    <title></title>
<style>
body {
margin: 0px;
padding:0px;
}

#main {
    margin-left: auto;
    margin-right: auto;
    width: 980px;
    height:600px;
}
.contents {
font-family: sans-serif,arial;
font-style: normal;
font-weight: 100;
font-variant: normal;
font-size: 11px;
}

.callout {
position: relative;
margin: 18px 0;
padding: 18px 20px;
background-color: #88BDE9;
border-radius: 6px;
max-width: 550px;
width: 300px;
font-family: sans-serif,arial;
font-weight: bolder;
font-variant: small-caps;
font-style: oblique;
}

.callout .notch{
position: absolute;
top: -10px;
left: 20px;
margin: 0;
border-top: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 10px solid #88BDE9;
padding: 0;
width: 0;
height: 0;
}

.border-callout{
border:1px solid #6D5151; 
padding:17px 19px;
box-shadow: 0px 0px 25px rgba(0, 0, 0,0.5);
}

.border-callout .border-notch{ 
border-bottom-color:#6D5151;
top: -11px;
}
</style>
  </head>
  <body>

          <div id="main">
              <div class="callout border-callout">
                This is a callout
                <p class="contents">And here is some more text so we can see the diiferent fonts and so on.</p>
                <b class="border-notch notch"></b>
                <b class="notch"></b>
              </div>
          </div>
<script type="text/javascript">
var $dragging = null, w, h;
    $(document.body).on("mousemove", function(e) {
        if ($dragging) {
            $dragging.offset({
                left: e.pageX - w,
                top: e.pageY - h
            });
        }
    });
    $(document).on('mousedown', 'div.callout', function(e){
        $dragging = $('div.callout'),
        w = $dragging.width() / 2,
        h = $dragging.height() / 2
    });
     $(document.body).on("mouseup", function (e) {
        $dragging = null;
    });
</script>
  </body>
</html>
4

1 回答 1

2

替换 mousedown 事件处理程序如下

$(document).on('mousedown', 'div.callout', function(e){
        $dragging = $('div.callout'),
        w = e.pageX-$(this).position().left,
        h = e.pageY-$(this).position().top

    });
于 2013-01-15T08:13:56.037 回答