简体   繁体   中英

Javascript swap 2 images

I'm busy with a project but know I'm stuck at some point. What I want to do is, when someone presses the home button, it changes its color. What I wanted to do is a swap from image 1 (white) to image 2 (blue) . So the person can see on which page he/she is. But when I put this code into the website, it won't show anything. When I press 2 times it will show the blue image. And when I press many times you see the white and blue image swapping. But it won't stand on the white image, only on the blue image

Here is the code I use. -->

<a href='' "<?php echo $this->createUrl("/admin/survey/sa/index"); ?>" onclick="edit()"><img id="img1" onclick="imageChange(this)"'<?php echo $sImageURL;?>home.png' alt='<?php $clang->eT("Default administration page");?>' />
<script type="text/javascript">
{
  var img1 = "/LimeSurvey/styles/scanyours/images/home.png";
  var img2 = "/LimeSurvey/styles/scanyours/images/home1.png";
}
{
  var imageChoice = 1;
}
function imageChange(element) 
{
  if (imageChoice == 1)
  {
    element.src = img2;
    imageChoice = 2;
  }
  else if (imageChoice == 2) 
  {
    element.src = img1;
    imageChoice = 1;
  }
}
</script></a>

Try to not embed the img tag in the anchor tag. Maybe the two onclick events disturb each other.

By the way: You should indent your code for better clarity.

EDIT:

I don't know the exact structure of your website, but if index.php only displays the homepage you could try this:

if ($_SERVER['PHP_SELF'] == 'index.php') {
  echo 'Show logo for homepage';
} else {
  echo 'Show logo for other pages';
}

When it works you could swap the echos with your element.src function. When it doesn't work check what is stored in $_SERVER['PHP_SELF'] when you are on your homepage and when you are on a different site and adapt the if statement.

If you have your image tag inside an anchor tag then even if your image replacement worked you would instantly be redirected to wherever your anchor links to.

Is that expected behaviour?

Here is a working example if you didn't have the anchor tag

http://jsfiddle.net/6LZpL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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