Javascript随机背景图片更改onload

标签 javascript jquery html css random

我在一个页面上有 6 个 ahref 框,它们都有不同大小的背景图像,我想做的是加载 3 个随机框 bg 图像文件扩展名,并将它们交换为 gif。所以每次页面刷新3张图片都不一样。我不完全确定如何执行此操作,因为我希望位置是随机的,但可以通过更改 url 来控制,而不是针对完全随机的图像进行更改。

最佳答案

要从您的列表中随机获取 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.

关于Javascript随机背景图片更改onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19089598/

相关文章:

javascript - 在 div 外部单击时让 overlay 和 div 正确淡入淡出?

javascript - typescript 错误 "Property ' 值'在类型 'HTMLElement' 上不存在”, "Property ' onclick'在类型 'Element' 上不存在”

html - CSS 背景渐变未按预期工作

html - 相对于固定 div 父级的固定 div 位置

php - 将 PHP 变量发送到 JavaScript 函数

javascript - 在将文件大小传递到服务器端之前在客户端进行处理

javascript - jQuery 将 JSON 值插入到具有特定类的元素

javascript - 如何根据我从ajax获得的json在select上添加禁用的select属性

javascript - 对 Shopify's/cart/add.js 的 Ajax POST 请求始终返回错误回调函数

jquery insertafter() 在 $(this) 变量中不起作用