繁体   English   中英

使用javascript更改css背景图像

[英]Change css background-Image using javascript

我有一个包含四个随机图像的图像阵列图像,

我想使用javascript更改类内容的CSS样式的背景图像

为此,我创建了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> 

更改

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

至:

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

在js中,必须将第一个字符-改为大写。 例如:

在CSS中: border-style

在js中: borderStyle

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

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

问题:

  1. 您无需创建img标签即可以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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM