简体   繁体   English

jQuery-可拖动DIV在浏览器窗口调整大小时不正确

[英]JQuery - Draggable DIV out of position on browser window resize

I have an oversized DIV element ('#draggableIMG') contained within a parent container ('#navScreen') . 我有一个过大的DIV元素('#draggableIMG')包含在父容器内('#navScreen') I use JQuery to drag the image. 我使用JQuery拖动图像。 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. 以下是我的JQuery代码,CSS代码和HTML代码。 How can I make the child DIV stay within the confines of its parent container upon resize? 调整大小后,如何使子DIV停留在其父容器的范围内?

HTML 的HTML

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

JQuery 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 的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. 但是,通过CSS操纵此图像的最佳方法。 You can use the " Background - Shorthand property " to define a css, without javascript manipulation. 您可以使用“ 背景-速记属性 ”来定义CSS,而无需进行JavaScript操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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