简体   繁体   English

缩放div并相对移动子元素

[英]Scale div and move child elements relatively

I need to scale a background image up or down and and also maintain the child divs inside them relative to the scale 我需要按比例放大或缩小背景图片,并且还要相对于比例尺保持子div在其中

The green squares should maintain their positions ( be aligned as they are initially to the image ) when i scale the parent div up or down 当我向上或向下缩放父级div时,绿色方块应保持其位置(与图像最初对齐)

The green divs should not change their size. 绿色div不应更改其大小。

Please let me know if you need more information 请让我知道是否需要更多信息

The JS fiddle is here http://jsfiddle.net/87cmgp8a/ JS小提琴在这里http://jsfiddle.net/87cmgp8a/

Html HTML

<div id="container">

    <div id="imageContainer">

        <div id="square1" class="square"></div>
        <div id="square2" class="square"></div>
        <div id="square3" class="square"></div>

    </div>
</div>
<br><br>
<button id="scaleup">Scale Up </button>
<button id="scaledown">Scale Down </button>

CSS 的CSS

#container {
    overflow: scroll;    
    height:350px;
    width:350px;
}

#imageContainer {
    background-image: url("http://www.portangelesschools.org/students/images/clip_image015.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
    height:400px;
    width: 400px;
}

.square {
    border: 1px solid;
    background-color: green;
    width: 35px;
    height: 35px;
    position: absolute;
}

#square1{ top: 8px; left: 87px; }
#square2{ top: 88px; left: 87px; }
#square3{ top: 165px; left: 87px; }

JS JS

var $imageContainer = $("#imageContainer");
var scaleFactor = 50;

$("button").click(function(){

    var id = $(this).attr("id");
    if( id === "scaleup" ) {
        $imageContainer.css({
            height: $imageContainer.height() + scaleFactor, 
            width: $imageContainer.width() + scaleFactor
        });
    }
    else {
        $imageContainer.css({
            height: $imageContainer.height() - scaleFactor, 
            width: $imageContainer.width() - scaleFactor
        });
    }

});

尝试设置CSS变换而不是高度和宽度:

transform: scale(x, y);

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

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