javascript - 页面刷新时更改图像有时会继续加载相同的图像

标签 javascript

我使用这个脚本在页面刷新时旋转和更改图像,它工作正常,但有时它会在更改为新图像之前多次加载相同的图像,有办法解决这个问题吗?

var theImages = [
      "1.jpg",
      "2.jpg",
      "3.jpg"
      ];
      function changeImage(){
      var size=theImages.length;
      var x = Math.floor(size*Math.random())
      document.getElementById("headerbanner").src = theImages[x];
    }

onload=changeImage

最佳答案

为了实现您需要的图像旋转行为,您需要“记住”页面加载之间的某些状态(即您之前所处的图像)。一种简单的方法是通过 LocalStorage API .

例如,您可以通过以下方式检索以前存储的 key 值:

let lastIndex = localStorage.getItem('last_index');

然后用它来控制阵列中显示的图像。您还可以使用:

localStorage.setItem('last_index', `${ lastIndex }`)

更新存储的值,以便下一页重新加载。这些可能会与您的代码集成在一起,如下所示:

  /* Get the last stored index, and parse to an integer */
  let lastIndex = Number.parseInt(localStorage.getItem('last_index'))

  if(Number.isNaN(lastIndex)) {
    /* If we got an invalid index (ie no previously stored value) set to default 0 */
    lastIndex = 0;
  }
  else {
    /* Otherwise increment the index counter. This is going to cause the image to
    change every page load */
    lastIndex ++; 
  }

  /* Remember the updated index for future reloads */
  localStorage.setItem('last_index', `${ lastIndex }`)

  var theImages = [
    "1.jpg",
    "2.jpg",
    "3.jpg"
    ];

    function changeImage(){

    var size=theImages.length;

    /* Use the modulo operators to get x based on lastIndex, and the total number
    of images */
    var x = lastIndex % size;

    document.getElementById("headerbanner").src = theImages[x];
  }

  window.onload=changeImage

请记住,LocalStorage API 将值设置为字符串,这就是为什么 Number.parseInt() 等是必要的。

关于javascript - 页面刷新时更改图像有时会继续加载相同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170278/

相关文章:

javascript - 使用免费的 jqGrid 4.15,无法过滤 false 的复选框

javascript - JQuery根据 anchor 标签的文本制作超链接

javascript - 键码 13 和键码 10 不工作

javascript - 谁拥有 javascript 中子框架的名称,父框架还是子框架?

javascript - Node 不允许 if 语句不带大括号?

javascript - 如何连接jquery内容中的两个过滤器?过滤器1和过滤器2连接结果

javascript - 如何在继续之前等待所有 promise 被解决

JavaScript 性格测验

javascript - 需要帮助来使用 JS 检索元素数组

javascript - JS 正则表达式删除 HTML 标签和内容