代码之家  ›  专栏  ›  技术社区  ›  Harper Creek

如何使缩放图像不经过其容器

  •  0
  • Harper Creek  · 技术社区  · 7 年前

    我试图使容器内的图像在放大时不会从容器底部超过15px。最好的方法是什么?我已经搞乱了getBoundingClientRect()之类的东西,但还没有找到实现它的关键。这是我的问题的一个例子。

    function myFunction() {
        var img = document.getElementById('image');
    
        img.style.WebkitTransform = ('scaleY(2.0)');
        img.style.width = img.getBoundingClientRect().width + 'px';
        img.style.width = img.getBoundingClientRect().height + 'px';
    }
    .rand {
        width:50px;
        height:50px;
        position:absolute;
        bottom:15px;
        left:45%;
    }
    
    div#test {
        margin:auto;
        border:2px solid red;
        width:200px;
        height:200px;
        object-fit: contain;
        overflow: hidden;
        position:relative;
    }
    <div id='test'>
        <img id='image' class='rand' src = 'https://www.purebuttons.com/cp/Pure_Buttons/html/images/squareprev.png'>
        </div>
       
        <button onclick='myFunction()'>CLICK</button>
    </body>

    因此,让图像完全缩放,越来越大,越来越小,但仍然保持在距离底部15px的位置,一旦缩放,图像就不会降低。谢谢你的帮助。

    2 回复  |  直到 7 年前
        1
  •  1
  •   ship shuk - www.shipshuk.com    7 年前

    你不需要改变属性,你可以改变职业来摆弄这个位置。

    function myFunction() 
    {
        var img = document.getElementById('image');
    
        //img.style.WebkitTransform = ('scaleY(2.0)');
        img.className = 'rand2';
    }
    .rand 
    {
        
        width:50px;
        height:50px;
        
        display:block;
        position:absolute;
        
        bottom:15px;
        left:45%;
        
        border:1px solid red;
    }
    
    .rand2
    {
        
        width:50px;
        height:50px;
        
        display:block;
        position:absolute;
        
        transform: scaleY(2.0);
        
        bottom:35px;
        left:45%;
        
        border:1px solid red;
    }
    
    div#test {
        margin:auto;
        border:2px solid red;
        width:200px;
        height:200px;
        object-fit: contain;
        overflow: hidden;
        position:relative;
    }
        2
  •  1
  •   Ry- Vincenzo Alcamo    7 年前

    可能最简单的方法是将变换设置为从底部开始,并使用 transform-origin :

    function myFunction() {
        var img = document.getElementById('image');
    
        img.style.transform = 'scale(2.0)';
    }
    .rand {
        width: 50px;
        height: 50px;
        position: absolute;
        bottom: 15px;
        left: 45%;
        transform-origin: center bottom;
    }
    
    #test {
        margin: auto;
        border: 2px solid red;
        width: 200px;
        height: 200px;
        overflow: hidden;
        position: relative;
    }
    <div id='test'>
        <img id='image' class='rand' src='https://i.stack.imgur.com/YxTTq.png'>
    </div>
       
    <button onclick='myFunction()'>CLICK</button>