簡體   English   中英

如何將背景圖像的 url 導入 css 文件?

[英]How can I import urls for background images to a css file?

我正在制作一個登陸頁面,其中包含來自 css 文件的五個圖像的幻燈片。 我希望 css 中的 url 來自一個數組,以便我可以通過更改數組來更改幻燈片中的哪些圖像。 背景圖片 URL 是否可以來自數組?

這是我希望 URL 來自數組的 css 片段:

.slideshow li:nth-child(1) { 
  background-image: url(http://i.imgur.com/K3mPv14.jpg) 
}
.slideshow li:nth-child(2) { 
  background-image: url(http://i.imgur.com/SBEmFpv.jpg);
  animation-delay: 10s; 
}
.slideshow li:nth-child(3) { 
  background-image: url(http://i.imgur.com/emvhOnb.jpg);
  animation-delay: 20s; 
}
.slideshow li:nth-child(4) { 
  background-image: url(http://i.imgur.com/2LSMCmJ.jpg);
  animation-delay: 30s; 
}
.slideshow li:nth-child(5) { 
  background-image: url(http://i.imgur.com/TVGe0Ef.jpg);
  animation-delay: 40s; 
}

更新根據 OP 請求添加了一些更詳細的步驟*

  1. 在根目錄中創建名為 random-arrays.php 的新文件。

  2. 打開/編輯新的 php 文件。

  3. 插入以下代碼,用您的圖像文件替換“file1.png”和“file2.png” 這些文件也應該在根目錄中。

<?php
  $img = array('file1.png', 'file2.png' ); // array of filenames

  $i = rand(0, count($img)-1); // generate random number size of the array
  $selectedImg = "$img[$i]"; // set variable equal to which random filename was chosen
?>

  1. 保存文件和/或放置在您網站的根目錄中。

  2. 打開你的 html 頁面並在 BODY 開始標記 () 之后添加以下代碼行:

<?php require './random-arrays.php';?>

  1. 將以下內容添加到您的 CSS 樣式表(或內聯,如果是內聯的),將類的名稱替換為您的類
.the_class_of_your_image_div {
background-image: url('<?php echo $selectedImg; ?'>
/* other css styling such as background-position, background-size, etc. */

享受背景圖像的隨機性。

背景圖片 URL 是否可以來自數組?

是的,但只能通過 javascript

// replace these with your images
const images = [
 'http://i.imgur.com/K3mPv14.jpg',
 'http://i.imgur.com/K3mPv14.jpg',
 'http://i.imgur.com/K3mPv14.jpg',
 'http://i.imgur.com/K3mPv14.jpg',
 'http://i.imgur.com/K3mPv14.jpg',
];

// slideshow
const slideshow = document.querySelector('.slideshow');

// adding your styles
slideshow.children.forEach((slideshowItem, index) => {
 slideshowItem.style.backgroundImage = `url(${images[index]})`;
 slideshowItem.style.animationDelay = `${10 * index}s`;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM