[英]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 請求添加了一些更詳細的步驟*
在根目錄中創建名為 random-arrays.php 的新文件。
打開/編輯新的 php 文件。
插入以下代碼,用您的圖像文件替換“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
?>
保存文件和/或放置在您網站的根目錄中。
打開你的 html 頁面並在 BODY 開始標記 () 之后添加以下代碼行:
<?php require './random-arrays.php';?>
.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.