【问题标题】:how to don't have the same bg 2 times in a row in this random background js如何在这个随机背景js中连续两次没有相同的bg
【发布时间】:2014-10-24 18:42:16
【问题描述】:

我遇到了与上一个问题相同的 bg js 的问题;这是js:

ChangeIt();
function ChangeIt()
{
    var totalCount = 12;
var num = Math.ceil( Math.random() * totalCount );
document.body.background ='http://adventureofucm.com/OtherSites/image_background/'+num+'.jpg';
}

因为我对js知之甚少,所以我问你是否可以看一下js并帮助我找到一个解决方案,以解决连续2次不显示相同的bg,仅此而已。希望您尽快回复我,或者如果您需要更多详细信息或其他内容,请发表评论。 编辑:在使用本地存储搜索解决方案后,我发现了一些有趣的东西,但我仍然没有编辑 js 的知识,谁能帮助我几分钟?

【问题讨论】:

  • 如果每次页面加载时脚本都在执行,那么它就无法知道上一个页面加载的是什么图片。如果您想在每次加载时使用不同的图片,那么您需要本地存储或会话存储之类的东西,您可以在其中存储选择的图片,以便在下一页加载时您可以再次检索该值并确保加载不同的图片。
  • 嗯,好的。所以我需要使用本地存储,我没有这个问题,只是不知道怎么做,如果没有问题你能帮我吗?

标签: javascript math random background probability


【解决方案1】:

我想这就是你要找的东西

function ChangeIt() {

  var HasStorage, PreviousPic, totalCount, num;

  //test if browser supports local storage
  if (typeof (localStorage) === 'object') {
     HasStorage = true;

     //get the previous picture name in the storage, if any
     PreviousPic = parseInt(localStorage.getItem('Previous'), 10);
  }

  totalCount = 12;
  num = Math.ceil( Math.random() * totalCount );

  //if there's a previous pic in storage then get a different one this time
  if (PreviousPic) {
      while (num === PreviousPic) {
          num = Math.ceil( Math.random() * totalCount );
      }
  }

  //store the pic used this load
  if (HasStorage) {
      localStorage.setItem('Previous', num);
  }

  document.body.background ='http://adventureofucm.com/OtherSites/image_background/'+num+'.jpg';
}

【讨论】:

  • 哇,这正是我需要的!刚刚尝试过,效果很好,第一次访问后图像加载速度也更快,我想我找不到更好的东西,说真的,tnx 很多:)
  • 附带说明,您还可以使用 cookie 来存储信息;这将使该功能在所有浏览器中都能正常工作,包括那些不支持 HTML5 的浏览器。
  • mmmh,不太确定,我认为如果没有 html5,该网站将无法运行,至少不是整个网站,所以我更喜欢使用本地存储,也是因为我不太喜欢 cookie,但是想想很多 tnx :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 2015-01-29
  • 2014-03-05
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
相关资源
最近更新 更多