使用JavaScript更改CSS背景图像

3
我有一个图片数组images,其中包含四张随机图片,
我想使用 JavaScript 更改类contents的 CSS 样式中的 background-image
为此,我创建了buildimagechangeImage,并在 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>

3个回答

4

问题:

  1. 您不需要创建标签来应用CSS样式中的background-image
  2. 您只应用了图像路径

解决方案:您需要将图像路径应用在URL()之间,就像普通的CSS背景图片一样。

请查看以下代码:

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() {
    document.getElementById('content').style.backgroundImage = 'url('+images[index]+')';
}

function changeImage() {
    index++;
    if (index >= images.length) index = 0;
    document.getElementById('content').style.backgroundImage = 'url(' + images[index] + ')';
}
.contents {
    width: 200px;
    height: 200px;
    border: 2px solid #FF0000;
}
<div class="contents" id="content"></div>
<button onclick="changeImage()">NextImage</button>


在本地系统的IDE中运行时,第二次更改没有发生。 - undefined
@Jupiter,这是因为 "https://picsum.photos/200/300/?random" 这个网站没有发送随机图片,而在应用其他图片时,它将正常工作。 - undefined

2

变量/属性名不能包含连字符(解释器会将其视为“减法”,但这没有意义)。在JavaScript DOM API中,与background-image对应的属性是backgroundImage

function buildImage() {
  var img = document.createElement('img');
  img.src = images[index];
  document.getElementById('content').style.backgroundImage = (img);
}

1
更改
document.getElementById('content').style.background - image = (img);

到:

document.getElementById('content').style.backgroundImage = (img);

在js中,你必须将-后的第一个字符改为大写。 例如: 在css中: border-style 在js中: borderStyle

不客气,@Jupiter。很高兴能帮到你 :) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接