javascript - 使用 javascript 更改 css 背景图像
问题描述
我有一个包含四个随机图像的图像阵列图像 ,
我想 使用 javascript更改类内容的 css 样式的背景图像。
为此,我创建了buildimage和changeImage 并且 onclick 试图更改它。
我怎样才能实现它?
var images = ['https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random', 'https://picsum.photos/200/300/?random'];
var index = 0;
function buildImage() {
var img = document.createElement('img');
img.src = images[index];
document.getElementById('content').style.background - image = (img);
}
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0];
index++;
index = index % 4; // This is for if this is the last image then goto first image I have 4 images so I've given 4 change accordingly
img.src = images[index];
}
.contents {
width: 100px;
height: 100px;
border: 2px solid #FF0000;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</style>
</head>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>
</body>
</html>
解决方案
变量/属性名称中不能有连字符(解释器会将其视为“减法”,但这没有意义)。JavaScript DOM API 中对应的属性background-image
是backgroundImage
:
function buildImage() {
var img = document.createElement('img');
img.src = images[index];
document.getElementById('content').style.backgroundImage = (img);
}
推荐阅读
- powershell - 在日志拖尾期间设置 Powershell 标题
- javascript - 如何在 HTML 和 JavaScript 中连续播放歌曲
- html - 使用绝对位置调整绘图画布的大小
- python - 在python中将自定义字符串格式的时间戳列转换为秒
- azure - 在自定义登录页面中添加自定义密码重置按钮 - Azure B2C
- python - 多输出预测(机器学习)
- flutter - Flutter 在 Widget 回调中传递 BuildContext
- c# - 如何在分配的变量值更改时停止变量更改C#
- javascript - 如何在 iframe 中更改音乐音量?
- asp.net-core - Asp.Net Core 3.1 - BackgroundService 在 IIS 启动/重新启动后不会自动启动