【问题标题】:How can I add an image to JS function?如何将图像添加到 JS 函数?
【发布时间】:2022-07-04 16:51:17
【问题描述】:

我正在尝试做一个吃豆人游戏,我在棋盘上添加布局的函数代码如下所示:

for (let i = 0; i < layout.length; i++) {
    const square = document.createElement('div')
    grid.appendChild(square)
    squares.push(square)
    // add layout to the board // 
    if (layout[i] === 0) {
        squares[i].classList.add('pac-dot')
    } else if (layout[i] === 1) {
        squares[i].classList.add('wall')
    } else if (layout[i] === 3) {
        squares[i].classList.add('strawberry')
    }
}

我想将图像添加到 classList Strawberry 中的正方形中,我尝试在 html 上创建一个 div 并使用 css 对其进行样式设置,但没有成功。我还尝试了带有 id 的 img 标签,但也没有成功。

如何将图像添加到正方形?

感谢您的帮助!

【问题讨论】:

  • const square = new Image(); square.src = 'url/to/your/image.png';
  • 那么DIV的样式有哪些。如果它没有显示图像,这似乎是你的问题。显示您的 CSS。
  • 看起来像这样 ` div.image { background-image: url("");背景重复:不重复;宽度:10px;高度:20px;边框半径:10px; } `

标签: javascript html css


【解决方案1】:

在草莓类中放置一个叫做背景图片的css样式

.strawberry {
background-image: url(""); 
/*
put image url in the url ("")
any url will work ex. images/myimage.jpg or www.web/image.jpg
*/
}

【讨论】:

  • 除了&lt;div class="straweberry"&gt;&lt;/div&gt; 之外,我应该用html 写什么?或者我应该在js中添加一些东西吗?因为我用 html 试过了,但是没用
  • @zsip 我相信你js你应该加squares[i].style.backgroundImage = "url('')"; 并在草莓类中取出背景图片你可以在添加背景图片后添加草莓类
【解决方案2】:

我通过像这样向 JS 主体添加另一个函数解决了这个问题;

        function addImageToSquare(div, imgSource, height, width) {
        let img = document.createElement("img");
        img.src = imgSource
        img.id = "picture"
        img.style.height = "25px"
        img.style.width = "25px"
        div.appendChild(img);
    }

我用这个调用了函数

addImageToSquare(squares[i], "images/strawberry.png")

else if (layout[i] === 3) 
 {squares[i].classList.add('strawberry') 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2017-01-20
    • 2013-01-12
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多