jquery - jquery随机背景 - 不同的eveytime
问题描述
我将随机背景设置为 div。我想知道当背景改变时是否有可能每次都会显示不同的背景,而不是从我的图像目录中复制。
非常感谢任何帮助。
$(function() {
var images = ['1.png', '2.png', '3.png'];
$('#sectionhero').css({
'background-image': 'url(bgimages/' + images[Math.floor(Math.random() * images.length)] + ')'
});
});
解决方案
你可以使用cookies来做到这一点,
https://github.com/js-cookie/js-cookie
$(function() {
var images = ['https://cdn.pixabay.com/photo/2017/09/14/11/13/water-2748657_960_720.png', 'https://images.panoramatours.com/pt/focus/49/50/1536/648/user_upload/Sehenswuerdigkeiten/Salzburg/Schloss_Leopoldskron__c__Panorama_Tours.jpg', 'https://media.studioatrium.pl/project/1030/willa-panorama-ii-wizualizacja-1350-5954e6b4080d8.jpg'];
if (Cookies.get('randomBackground') == undefined) {
Cookies.set('randomBackground', 0); // if there's no cookie, it will display the first image
} else {
// if there's cookie, get a new one
var randomBackground = getRandomBackground();
Cookies.set('randomBackground', randomBackground);
}
$('#sectionhero').css({
'background-image': 'url(' + images[Cookies.get('randomBackground')] + ')'
});
function getRandomBackground() {
var rand = Math.floor(Math.random() * images.length);
// if the value is the same as existing cookie value, get another one
if (rand == Cookies.get('randomBackground')) return getRandomBackground();
else {
return rand;
}
}
});
推荐阅读
- node.js - 检索单个对象而不是列表/数组
- c++ - 为什么 OpenCV 的 polarWarp 会在某些图像中引入伪影?
- rust - 如何为 SPECS 框架编写单元测试而不将代码拆分为单独的函数?
- apify - 我无法将代理与 http:username:password@host:port 一起使用
- r - R使用rvest从网页中提取文本
- r - 将命名向量转换为命名列表
- mongodb - MongoDB多个线程同时更新同一个文档
- javascript - Electron 应用程序中的格式 () 问题
- email - RunDeck 在重新尝试发送失败电子邮件的工作时会做什么?
- powershell - PowerShell:在现有别名的基础上向 AD 组(proxyAddresses)添加新别名