jquery - 图像大于容器时的可拖动图像

时间:2010-10-25 15:17:04

标签: javascript jquery jquery-ui

当图像比容器大时,使图像可拖动会做一些非常古怪的事情......有没有人知道解决这个问题的方法?

这是我的代码......

<script type='text/javascript' src="scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="scripts/jquery-ui.js"></script>

<script type="text/javascript">

    $(document).ready(function() {

        $("img").draggable({ containment: "div", scroll: false });

    });

</script>

<style type="text/css">
    div {
        width:500px; 
        height:423px; 
        position:relative; 
        overflow:hidden;
    }
</style>

和......

<div>
    <img src="images/map.jpg" width="1000" height="845" alt="Map" />
</div>

3 个答案:

答案 0 :(得分:5)

如果您手动设置边界,它会起作用:

$("img").draggable({ containment: [0, 0, 500, 423], scroll: false });

答案 1 :(得分:1)

我选择通过以下方式动态设置包含父和子大小的包含,JSFiddle Here

$(function () {
    $("div[id='dragx']").draggable({
    drag : function(event,ui){
      var parent = ui.helper[0].parentNode;

      var dragWidth = ui.helper[0].clientWidth;
      var parentWidth = parent.clientWidth;
      var dragHeight = ui.helper[0].clientHeight;
      var parentHeight = parent.clientHeight;

      var widthDifference = dragWidth - parentWidth;
      var heightDifference = dragHeight - parentHeight;

      if(ui.position.left > 0) ui.position.left = 0;
      else if(ui.position.left < -widthDifference) ui.position.left = -widthDifference;

      if(ui.position.top > 0) ui.position.top = 0;
      else if(ui.position.top < -heightDifference) ui.position.top = -heightDifference;

      }
    });
});

答案 2 :(得分:0)

我不确定你是否正确使用拖拽。它的关键是拾取图像并将其放在某处。如果图像大于容器,你怎么知道你把它放在哪里?这与你想要抓取图像并在拖动时使容器滚动一样不同。

现在,那说,我认为这是一个错误(或者可能是一个特征?),如果内部元素较大,外边缘会与容器边缘对齐。

您是否尝试在单击并拖动鼠标时滚动地图?