【问题标题】:Need to sort list of images in ascending order in Javascript需要在Javascript中按升序对图像列表进行排序
【发布时间】:2014-12-17 20:39:39
【问题描述】:

感谢你们,每次刷新时,我都能使用下面的 javascript 从我的网站随机更改背景图片。这很痛苦,因为图像位置在 .css 文档中,而不是在 .html 中。

我需要图像以升序显示,“1.jpg、2.jpg、3.jpg 等”一旦到达最后一个数字,它就会再次以 1.jpg 开始。

我已经研究和试错了 2 天,但没有运气。

 <script type="text/javascript">
var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'];
$('#parallax-header').css({'background-image': 'url(images/parallax/' +          
images[Math.floor(Math.random() * images.length)] + ')'});
</script>

【问题讨论】:

    标签: javascript list sorting


    【解决方案1】:

    为此,浏览器需要记住刷新前上一张图片的内容。这可能发生在 cookie 或 localStorage 上。如果您的数组中的图像已经按升序排列,您只需将图像的最后一个 index 存储在浏览器的存储空间中,然后在每次刷新时将其递增 1。

    jsfiddle:

    // coerce the index to number just in case; if it is null, set it to 0
    var i = +localStorage.getItem('i') || 0,
        next = 0,
        images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'];
    
    if(i === images.length - 1) {
        next = 0;
    } else {
        next = i++;   
    }
    
    localStorage.setItem('i',next);
    
    $('#parallax-header').css({'background-image': 'url(images/parallax/' +          
    images[i] + ')'});
    

    这是来自 MDN 的 localStorage 兼容性表:

    如果您需要 polyfill,请查看Web Storage (LocalStorage and SessionStorage) from HTML5 Cross Browser Polyfills

    【讨论】:

      【解决方案2】:

      jsBin demo

      使用 localStorage(类似于 Josh 的回答)

      var images = ['foo.jpg', 'bar.jpg', 'baz.jpg']; // Add as many as y w
      var n  = +localStorage.imgN || 0; // Use `0` if localStorage was never set before
      $('#parallax-header').css({backgroundImage: 'url(images/parallax/' + images[n] + ')'});
      localStorage.imgN = ++n % images.length; // re-set by incrementing and loop
      

      【讨论】:

        猜你喜欢
        • 2019-07-23
        • 2021-10-10
        • 2013-10-16
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        相关资源
        最近更新 更多