如何用div扩展div的内容?

时间:2016-06-17 21:41:08

标签: javascript jquery html css

我有一个父div包含一个带有一堆"孔的图像"在里面。每个洞都有一个子div,用于定义这些孔的确切大小。在这些洞中,我有文字,我已经设置了位置:绝对,以便它们恰好适合孔。但是,当我调整父div的大小时,内容根本不会缩放,并且它们保持相同的大小。他们不再在洞里面了。

2 个答案:

答案 0 :(得分:2)

用户'%'作为一个单位而不是像素

<div id="ParentDiv">
    <img src="../610614-spring-forest.jpg">
    <div class="hole1">Tree1</div>
</div>

#ParentDiv{
        max-width:900px;
        position: relative;
    }
    img{
        width: 100%;
        height: auto;
    }
    .hole1{
        position: absolute;
        left:2.75%;
        top:23.87%;
    }

对于这种情况,您可以使用Viewport Hieght或Viewport Width单位。以下是您可以使用的示例。

#ParentDiv{
        max-width:100vw;
        max-height:100vh;
        position: relative;
    }
    img{
        width: 100%;
        height: auto;
    }
    .hole1{
        position: absolute;
        /*left:2.75%;
        top:23.87%;*/
        left:2.75vw;
        top:23.87vh;
    }

尝试使用类似的,希望你能得到理想的结果。

答案 1 :(得分:1)

您可以使用名为transform的CSS属性,而不是直接更改大小。

当您需要设置图像的大小时:

// this is the container the image and its text is in
imageContainer = document.getElementById('myDiv');
// original size of image
origX = 400;
origY = 300;
// size you need it to change to
newX = 800;
newY = 600;
/*
Tells CSS to stretch from the top-left edge of the object, so it won't stretch off the left side of the screen
Best way to change value would be percentages
Value of '0 0' sets origin to top-left
Value of '100% 100%' sets origin to bottom-right
*/
imageContainer.style.transformOrigin = '0 0';
//the following is just one string, broken into multiple lines for easy explanation
// tells CSS that the transform type is scale
imageContainer.style.transform = 'scale(' +
    // tells CSS how many times normal size to widen image. in this case evaluates to 2, since 800/400 is 2, making image 2x wider
    (newX / origX) + ',' +
    // tells CSS how many times normal size to heighten image. in this case evaluates to 2, since 600/300 is 2, making image 2x taller
    (newY / origY) + ')';

假设您没有主要的性能削弱功能,这将非常有用。如果你有很多事情发生,那只会有点慢。

未注释:

imageContainer = document.getElementById('myDiv');
origX = 400;
origY = 300;
newX = 800;
newY = 600;
imageContainer.style.transformOrigin = '0 0';
imageContainer.style.transform = 'scale(' + (newX / origX) + ',' (newY / origY) + ')';
相关问题