简体   繁体   English

JavaScript随机背景图片更改加载

[英]Javascript random background image change onload

I have 6 ahref boxes on a page which all have different sized background images, what I would like to do is onload get 3 random boxes bg image file extensions, and swap them over for gifs. 我在页面上有6个ahref框,每个框都有不同大小的背景图像,我想做的是onload获得3个随机框的bg图像文件扩展名,并将它们交换为gif。 So every time the page refreshes 3 images are different. 因此,每次页面刷新3张图像都是不同的。 Im not entirely sure how to do this, as i want the positions to be random, but have the control by changing the urls and not changing for completely random image. 我不完全确定如何执行此操作,因为我希望位置是随机的,但是可以通过更改url而不是完全随机的图像来进行控制。

To get a random 3 nodes from your list you can select them, convert them to an array then pick one by index between 0 and nodeList.length: 要从列表中随机获取3个节点,可以选择它们,将它们转换为数组,然后按0到nodeList.length之间的索引选择一个:

(function (document) {
    var boxes = document.getElementsByClassName('box'),
        background = '',
        index = 0;

    // Convert the nodeList to an Array
    boxes = Array.prototype.slice.call(boxes);

    // Returns a random integer between min and max
    // Using Math.round() will give you a non-uniform distribution!
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    for (var i=0; i<3; i++) {
        // Pick a random node
        index = getRandomInt(1, boxes.length) - 1;
        // Background
        background = document.defaultView.getComputedStyle(boxes[index])
            .backgroundImage
            .replace('.jpg', '.gif');
        boxes[index].style.cssText = "background-image:" + background;
        // Remove that node so we don't get it again
        boxes.splice(index, 1);
    }

}(document));

Here's a Fiddle to show it in action. 这是一个小提琴,以展示其实际效果。

var randomNum = Math.floor(Math.random() * 6)

This will generate a random number between 0-5. 这将生成一个介于0-5之间的随机数。 So you can go ahead and select the respective child 因此,您可以继续选择相应的孩子

$( "ul li:nth-child(randomNum )" ).css('background-image', 'url(http://url you want.com)')

If you want random images also try either naming the images so that you can use another random variable to get the images by appending them to the url() 如果您想要随机图像,也可以尝试命名图像,以便可以使用另一个随机变量将图像附加到url()来获取图像。

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

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