gpt4 book ai didi

javascript - 使用 javascript 更改 css 背景图像

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:29 25 4
gpt4 key购买 nike

我有一个图像数组 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>

最佳答案

问题:

  1. 您不需要创建 img 标签来应用 background-imageCSS 样式
  2. 您仅应用图像路径

Solution : You need to apply image path between URL() just like normal CSS background image applies

检查下面的代码:

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>

关于javascript - 使用 javascript 更改 css 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52510749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com