Drag a zoomed image within a div clipping mask using jQuery draggable?

为君一笑 提交于 2019-12-02 18:53:29
Lauri
$(this).draggable({
    drag: function(event, ui) {
        if (ui.position.top > 0) {
            ui.position.top = 0;
        }
        var maxtop = ui.helper.parent().height() - ui.helper.height();
        if ( ui.position.top < maxtop) {
            ui.position.top = maxtop;
        }
        if ( ui.position.left > 0) {
            ui.position.left = 0;
        }
        var maxleft = ui.helper.parent().width() - ui.helper.width();
        if ( ui.position.left < maxleft) {
            ui.position.left = maxleft;
        }
    }
});

Ok. I've got this working now. This is how to set up a draggable image within a div clipping mask so that it is completely dynamic and works no matter how you resize the page.

The HTML/CSS

<div id="my-mask" style="width: 200px; height: 200px; overflow: hidden;">
   <img id="my-image" src="big-image.jpg" width="1000" height="1000"/>
</div>

The jQuery/JavaScript

// Make sure it always starts @ zero position for below calcs to work
$("#my-image").css({top: 0, left: 0});

var maskWidth  = $("#my-mask").width();
var maskHeight = $("#my-mask").height();
var imgPos     = $("#my-image").offset();
var imgWidth   = $("#my-image").width();
var imgHeight  = $("#my-image").height();

var x1 = (imgPos.left + maskWidth) - imgWidth;
var y1 = (imgPos.top + maskHeight) - imgHeight;
var x2 = imgPos.left;
var y2 = imgPos.top;

$("#my-image").draggable({ containment: [x1,y1,x2,y2] });
$("#my-image").css({cursor: 'move'});

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!