【问题标题】:How can I have an image in the background of 4 div elements with javascript?如何使用 javascript 在 4 个 div 元素的背景中创建图像?
【发布时间】:2021-11-06 16:23:20
【问题描述】:

我想要一个高度为 45 像素、宽度为 (45*4) 像素的图像作为 4 个 div 元素的背景。所有这些 div 元素都是 45px 的正方形。我的想法是给每个 div-background 图像的 i-esime 四分之一部分。我正在尝试使用代码中显示的 div 元素的背景位置来获得所需的效果。不幸的是,结果以随机顺序显示图像的 4 个部分,而不是按顺序显示。 代码如下:

<html>
    <head>
        <meta charset="utf-8">
        <script>

            function begin(){

                var caselle = document.getElementsByTagName('div');

                for (i=0; i<4; i++){
                    caselle[i].style.display="inline-block";
                    caselle[i].style.height="45px";
                    caselle[i].style.width="45px";
                    caselle[i].textContent=" ";
                    caselle[i].style.backgroundImage="url(corazzata.jpg)";
                    caselle[i].style.backgroundSize="180px 45px";
                    caselle[i].style.backgroundPosition=(i*45)+"px 45px";
                }
            }
        </script>
    </head>
    <body onload="begin()">
        <div id="1"></div>
        <div id="2"></div>
        <div id="3"></div>
        <div id="4"></div>
        <div id="5"></div>
        <img id="barca1" src="corazzata.jpg">
    </body>
</html>```

【问题讨论】:

  • 您是否尝试过将图像设置为父 div 的背景并让这些 div 内部没有背景?

标签: javascript html css


【解决方案1】:

您是否尝试过将图像设置为父 div 的背景并让这些 div 内部没有背景?

这是一个例子 https://jsfiddle.net/mr_bobz/6zyw3j2d/

<html>
    <head>
        <meta charset="utf-8">       
    </head>
    <body >
      <div style="background-color: yellow; background-image: url('https://media.istockphoto.com/photos/colored-powder-explosion-on-black-background-picture-id1140180560?k=20&m=1140180560&s=612x612&w=0&h=X_400OQDFQGqccORnKt2PHYvTZ3dBLeEnCH_hRiUQrY=');  height: 250px; background-repeat: no-repeat;">
        <div style='height: 50px; color: white' id="1">DIV 1</div>
        <div style='height: 50px; color: white' id="2">DIV 2</div>
        <div style='height: 50px; color: white' id="3">DIV 3</div>
        <div style='height: 50px; color: white' id="4">DIV 4</div>
        <div style='height: 50px; color: white' id="5">DIV 5</div>
      </div>       
    </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多