[英]How can I add an image to JS function?
我正在嘗試做一個吃豆人游戲,我在板上添加布局的函數代碼如下所示:
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
標簽,但也沒有成功。
如何將圖像添加到正方形?
謝謝您的幫助!
我通過向 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')
在草莓類中放置一個名為背景圖像的 CSS 樣式
.strawberry {
background-image: url("");
/*
put image url in the url ("")
any url will work ex. images/myimage.jpg or www.web/image.jpg
*/
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.