简体   繁体   中英

JQuery - Draggable DIV out of position on browser window resize

I have an oversized DIV element ('#draggableIMG') contained within a parent container ('#navScreen') . I use JQuery to drag the image. The user is supposed to move the element and the element is constrained within the container. So far, so good:

图片全尺寸

However, when I manually change the browser window the image moves out of position on the bottom-right corner, exposing the image it overlays.

图片破损代码

Below is my JQuery code, CSS code and HTML code. How can I make the child DIV stay within the confines of its parent container upon resize?

HTML

<div id="navScreen" class="navigation-screen">
    <div class="navigation-draggable-image" id="draggableIMG">
         <img src="{{imgSrc}}" alt="" class="responsive-image" />
    </div>
</div>

JQuery

 $(document).ready(function() {

    var parentPos = $('#navScreen').offset();
    var childPos = $('#draggableIMG').offset();
    var top = -(parentPos.top);
    var left = -(parentPos.left);

    $('#draggableIMG').css({ top: top + 'px', left: left + 'px', position: 'absolute', cursor: 'pointer'});

    $('#draggableIMG').draggable({
        drag: function(event, ui) {
            if (ui.position.top >= 0) {
                ui.position.top = 0;
            }
            if (ui.position.left > 0) {
                ui.position.left = 0;
            }
            if (ui.position.left < -(parentPos.left * 2)){
                ui.position.left = -(parentPos.left * 2);
            }
            if (ui.position.top < -(parentPos.top * 2)){
                ui.position.top = -(parentPos.top * 2);
            }
        },
        scroll: false
    });
  });

CSS

#draggableIMG {
    height:200%;
    width:200%;
}

#navScreen {
    height:100%;
    width:100%;
    position:relative;
    overflow:hidden;
}

You can use the function:

 $(window).resize(function(){
//you function to here
});

To recalculate the new position of image.

However, the best way to manipulate this image by way of CSS. You can use the " Background - Shorthand property " to define a css, without javascript manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM