CSS中图片旋转超出父元素解决办法

下面的两种解决办法都会导致图片缩小,可以给图片进行初始化的宽高设置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html,body {
            margin: 0;
            padding: 0;
        }
        #box {
            box-sizing: border-box;
            width: 100%;
            height: 240px;
            background: pink;
        }
        #image {
            transform: rotate(0);
            object-fit: contain;
        }
        #btn {
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <div id="box">
        <img id="image" src="https://www.runoob.com/images/pulpit.jpg" alt="">
        <!-- <img id="image" src="https://pics0.baidu.com/feed/c2cec3fdfc039245259830d9727ca5c77c1e2521.jpeg@f_auto?token=b910f4287521294b9469788c77a3ac93&s=A12326BEC5137FDECCBC8DC1030060BB" alt=""> -->
    </div>
    <button id="btn">旋转</button>
</body>
<script>
    window.onload = () => {
        let btn = document.getElementById('btn')
        let image = document.getElementById('image')
        let box = document.getElementById('box')
        let childRawWidth = image.offsetWidth // 原始的图片宽
        let childRawHeight = image.offsetHeight  // 原始的图片高
        let deg = 0 
        btn.onclick = function() {
            if (deg > 360) {
                deg = 0
            } else {
                deg += 90
            }
            // 方法一:使用 scale -- 父元素的高度不固定
            // let childWidth = image.offsetWidth
            // let childHeight = image.offsetHeight
            // let scalePix = 1
            // if (childWidth > childHeight) {
            //     scalePix = childHeight / childWidth
            // } else {
            //     scalePix = childWidth / childHeight
            // }
            // image.style.transform = `rotate(${deg}deg) scale(${scalePix}, 1)`
            // 方法二:将图片重新设置宽高 -- 父元素的高度固定
            let parentWidth = box.offsetWidth
            let parentHeight = box.offsetHeight
            if (childRawWidth > childRawHeight) {
                image.style.width = childRawHeight + 'px'
            }
            image.style.transform = `rotate(${deg}deg)`
        }
    }
</script>
</html>

原始图片:
CSS中图片旋转超出父元素解决办法_第1张图片

超出的效果图:
CSS中图片旋转超出父元素解决办法_第2张图片

解决之后的效果图:
CSS中图片旋转超出父元素解决办法_第3张图片

你可能感兴趣的:(JS,css,前端)