简体   繁体   English

使用JavaScript刷新页面时切换图像

[英]Switch image when page refreshes using Javascript

How to switch an image when the page refreshes, using Javascript? 页面刷新时如何使用Javascript切换图像?

Let's say I have 2 images: 假设我有2张图片:

  • ImageA.jpg ImageA.jpg
  • ImageB.jpg ImageB.jpg

I want to switch those images at locationA and locationB when the page is refreshed. 刷新页面后,我想在locationA和locationB上切换这些图像。

Simulation: 模拟:

- Page Refresh #1
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>


- Page Refresh #2
<img id='locationA' src='ImageB.jpg'>
<img id='locationB ' src='ImageA.jpg'>


- Page Refresh #3
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>

[Update #1] [更新#1]

I try this implementation, but it doesn't work. 我尝试了此实现,但没有用。 Could anyone tell me whats wrong with this code? 谁能告诉我这段代码有什么问题吗?

<html>
  <head>
    <script type="text/javascript">
      var images = [];
      images[0] = "I_am_Super_Magnet%21.jpg";
      images[1] = "World_In_My_Hand%21.jpg";

      var index = sessionStorage.getItem('index');
      if(index) index = 0;

      if(index==0)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index+1];
        index = index + 1;
      }
      else if(index==1)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index-1];
        index = index - 1;
      }
     sessionStorage.setItem('index', index);
    </script>
  </head>
  <body>
    <img id='locationA' src=''>     
    <img id='locationB' src=''>
  </body>
</html>

[Update #2] [更新#2]

Tested on: 经过测试:

  • FF 16.0.1 --> Working! FF 16.0.1->正常工作!
  • IE 8 --> doesn't work IE 8->不起作用

Here is the code: 这是代码:

<html>
  <head>
    <script type="text/javascript">
    function switchImage()
    {
      var images = [];
      images[0] = "I_am_Super_Magnet%21.jpg";
      images[1] = "World_In_My_Hand%21.jpg";

      var index = sessionStorage.getItem('index');

      if(index == null) index = 0;//set index to zero if null

      index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.

      if(index == 0)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index+1];
        index = index + 1;
      }
      else if(index == 1)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index-1];
        index = index - 1;
      }
      sessionStorage.setItem('index', index);
    }
    </script>
  </head>
  <body onload="switchImage()">
    <img id='locationA' src='src_locationA'>        
    <img id='locationB' src='src_locationB'>
  </body>
</html>

Thanks to Jack for the clue! 感谢杰克的线索! and thanks to Jon Kartago Lamida for the sample! 并感谢Jon Kartago Lamida提供的样本!

Thanks. 谢谢。

Set a flag variable in your cookie ( Check Javascript Cookie SO Question for setting a cookie ). 在您的Cookie中设置一个标记变量(有关设置Cookie的信息,请参阅Javascript Cookie SO问题)。

Every time the page loads, ( in your onload function ) check the value of the flag. 每次页面加载时,(在onload函数中)检查标志的值。

  1. Say if value is 0 . 说,如果值是0。 Show ImageA in LocationA. 在LocationA中显示ImageA。 Then invert the flag value to 1. 然后将标志值反转为1。
  2. Else if value is 1 . 否则,如果值为1。 Show ImageB in LocationA. 在LocationA中显示ImageB。 Then invert the flag value to 0. 然后将标志值反转为0。

The flag value will be stored in your cookie. 标志值将存储在您的cookie中。

Hope this helps, Shoubhik 希望对您有帮助,Shoubhik

I try to give example according to Jack, using localStorage. 我尝试根据杰克,使用localStorage给出示例。 Most modern browser have support this. 大多数现代浏览器都支持此功能。 I haven't this this code yet, but more or less should be like this. 我还没有这个代码,但是或多或少应该是这样的。

 <html>
  <head>
    <script type="text/javascript">
     function init(){

var imageA = 'imageA.jpg';
var imageB = 'imageB.jpg';

// state maintaned using localStorage
var toggle = localStorage.getItem('toggle');

if(toggle) toggle = "A"; // if no state yet, initialize

if(toggle == "A"){
toggle = "B";
document.getElementById('locationA').src=imageA;
document.getElementById('locationB').src=imageB;
}else{
toggle = "A";
document.getElementById('locationA').src=imageB;
document.getElementById('locationB').src=imageA;
}
// put state back to local storage
localStorage.setItem('toggle', toggle);
}
    </script>
  </head>
  <body onload="init()">
    <img id='locationA' src=''>     
    <img id='locationB' src=''>
  </body>
</html>

Base on Damien_The_Unbeliever comment I create this answer post for my own question. 基于Damien_The_Unbeliever评论,我为自己的问题创建了此答案帖子。

This is final working solution that I use. 这是我使用的最终工作解决方案。

[Update #3] [更新#3]

Tested on: 经过测试:

  • FF 16.0.1 --> Working! FF 16.0.1->正常工作!
  • IE 8 --> Working! IE 8->工作正常!
  • Chrome 24 --> Working! Chrome 24->工作正常! (Note: this browser need a little extra effort to make it can read cookie. see this link ) (注意:该浏览器需要付出一些额外的努力才能使其能够读取Cookie。请参阅此链接

Basically the code is still same as Update #2, the different is I use cookie instead of sessionStorage . 基本上,代码仍然与Update#2相同,不同之处在于我使用cookie而不是sessionStorage Here is the complete code: 这是完整的代码:

<html>
  <head>
    <script type="text/javascript">
    function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name,"",-1);
    }

    function switchImage()
    {
      var images = [];
      images[0] = "I_am_Super_Magnet%21.jpg";
      images[1] = "World_In_My_Hand%21.jpg";

      var index = readCookie('index'); //sessionStorage.getItem('index');

      if(index == null) index = 0;//set index to zero if null

      index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.

      if(index == 0)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index+1];
        index = index + 1;
      }
      else if(index == 1)
      {
        document.getElementById("locationA").src=images[index];
        document.getElementById("locationB").src=images[index-1];
        index = index - 1;
      }
      createCookie('index', index); //sessionStorage.setItem('index', index);
    }
    </script>
  </head>
  <body onload="switchImage()">
    <img id='locationA' src='src_locationA'>        
    <img id='locationB' src='src_locationB'>
  </body>
</html>

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

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