如何引用脚本中引号内的图像

How to reference an image within quotation marks in a script

本文关键字:图像 脚本 何引用 引用      更新时间:2023-09-26

我试图引用一个图像,而不是在html页面中的脚本标记中使用文本。我正在尝试使用图像代替文本作为按钮。按下按钮后,它将变为文本"Paused",如下所示。

pauseButton.innerHTML = "Paused";

当再次按下时,会显示单词"Pause"(暂停)。

pauseButton.innerHTML = "Pause";

相反,我希望它显示我创建的图像。此代码显示了我尝试引用图像的部分。

pauseButton.innerHTML = "url(Images/pausebackground.png)";

它不显示图像,而是以文本的形式显示"url(Images/pausebakground.png)"。

如何引用引号内的图像?

您需要将HTML代码放入innerHTML中(顾名思义)。使用<img>标签:

pauseButton.innerHTML = '<img src="Images/pausebackground.png">';

HTML中的图像使用<img>标记,该标记具有指向图像URL的src属性,如下所示:

<img src="Images/pausebackground.png">

要将图像插入HTML中,可以使用innerHTML,但最好添加一个实际的HTML元素:

var image = document.createElement('img'); // Create the HTML element
image.setAttribute('src', 'Images/pausebackground.png'); // Set the image src
pauseButton.appendChild(image); // Place it inside the button

要设置不同的图像,只需更改图像标记上的src属性即可。

innerHTML属性将更改元素内部的html

<div>
  Here is the inner html.
</div>

如果你想在内部html中添加一个图像,你可以使用一个普通的图像标签,但请记住,只需设置innerHTML就会删除其中的任何内容。

pauseButton.innerHTML = '<img src="Images/pausebackground.png" />'

如果你想使用图像作为按钮的背景(我想你更愿意这样做),你可以将图像设置为元素style.backgrubndImage属性,或者创建一个css类,并在需要时将其添加到按钮中(通过js)。

// Alt 1, changing the style of the element:
pauseButton.style.backgroundImage = "url(Images/pausebackground.png)";
// Alt 2, creating a css class and adding it to the element when needed:
// CSS.
.my-special-button-class {
  background-image: url(Images/pausebackground.png)
}
// JS.
pauseButton.classList.add("my-special-button-class");