用js设置图片宽度

JavaScript011

用js设置图片宽度,第1张

这种情况用CSS来控制最合适。例如你想让初始图片显示为100px*100px,则:

<img src="images/pic.png" width="100" height="100" />

或者:

<img src="images/pic.png" style="width:100pxheight:100px" />

当页面中图片非常多,且要求每张图片的大小依据其父容器来固定怎么办?可以使用max-weight:

img {max-weight:100%}

这样图片会自动缩放到和其父容器等宽。

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    <style>

        div div {

            width: 30px

            height: 30px

            display: inline-block

            border: 1px solid black

            background-repeat: no-repeat

            background-size: 300% 300%

        }

        #img1 {

            background-position: top left

        }

        #img2 {

            background-position: top

        }

        #img3 {

            background-position: top right

        }

        #img4 {

            background-position: center left

        }

        #img5 {

            background-position: center

        }

        #img6 {

            background-position: center right

        }

        #img7 {

            background-position: bottom left

        }

        #img8 {

            background-position: bottom

        }

        #img9 {

            background-position: bottom right

        }

    </style>

</head>

<body>

    <div>

        <div id="img1"></div>

        <div id="img2"></div>

        <div id="img3"></div>

    </div>

    <div>

        <div id="img4"></div>

        <div id="img5"></div>

        <div id="img6"></div>

    </div>

    <div>

        <div id="img7"></div>

        <div id="img8"></div>

        <div id="img9"></div>

    </div>

    <button>next</button>

</body>

<script>

    let arr = ["http://iconfont.alicdn.com/t/1522400286994.jpg@100h_100w.jpg", "http://iconfont.alicdn.com/t/1510710350863.png@100h_100w.jpg", "http://iconfont.alicdn.com/t/1553563063102.jpg@100h_100w.jpg"]

    let num = 0

    let imgFun = () => {

        document.querySelectorAll("div div").forEach(item => {

            item.style.backgroundImage = 'url(' + arr[num] + ')'

        })

    }

    imgFun()

    document.querySelector("button").onclick = () => {

        if (num < arr.length - 1) {

            num++

        } else {

            num = 0

        }

        imgFun()

    }

</script>

</html>

 请采纳