Javascript simple onclick image sharing

I am trying to use Javascript to replace an image while I can get it from A to B, but haven't returned.

Here is what I use to create one swap:

<img src="pic1.png" name="pic" onclick="window.document.pic.src='pic2.png';"/>

This reduces image 1 to image 2, which is quite simple. But I want to return to image 1 by clicking on the new image 2. I tried to use this:

<img src="pic1.png" name="pic" onclick="
if (window.document.pic.src='pic1.png'){
window.document.pic.src='pic2.png';
} 
else if (window.document.pic.src='pic2.png'){
window.document.pic.src='pic1.png';
}"/>

In this case, it does not work. It will switch to pic2, but will not switch to pic1. Does this have anything to do with onclick? My if statements? Thanks

+3
source share
6 answers

  window.document.pic.src , http://localhost/pic1.png   if (window.document.pic.src== 'pic1.png'). .  

<script type="text/javascript">
function test()
{
    alert(window.document.pic.src);
     //alert msg print like http://localhost/test/pic1.png
    if (document.pic.src=='http://localhost/test/pic1.png'){

document.pic.src='pic2.png';
} 
else if (document.pic.src=='http://localhost/test/pic2.png'){

document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>
+1

... .

<script>
var onImg= "on.jpg";
var offImg= "off.jpg";
</script>
<img src="on.jpg" onclick="this.src = this.src == offImg ? onImg : offImg;"/>
+10

== in if condition

if (window.document.pic.src == 'pic1.png'){
window.document.pic.src='pic2.png';
} 
else if (window.document.pic.src =='pic2.png'){
window.document.pic.src='pic1.png';
}"/>
+2
  • window.document.pic.src='pic1.png' pic1.png . .

  • , , . id.

  • javascript onclick. javasctipt function

:

img:

<img src="pic1.png" name="pic" id="pic" onclick="swap()"/>

javascript

<script>
function swap()
{
   if (document.getElementById("pic").src.endsWith('pic1.png') != -1)  //==:Comparison
   { 
      document.getElementById("pic").src = "pic2.png"; //=:assignment   
   } 
   else if (window.document.pic.src.endsWith('pic2.png') != -1) 
   { 
      document.getElementById("pic").src = "pic1.png"; 
   }
}
</script>
+2

, , if else, , if else, , src "pic2.png", "pic1.png", , pic2.png, .

<html>
<head>
<script type="text/javascript">

function swap() {
    window.document.pic.src='pic2.png';
}
</script>

</head>
<body>
<img src="pic1.png" name="pic" onclick="swap()"> 
</body>
</html>
0

.

<html>
<head>
<title>Swapping Images</title>
</head>
<body>
<img id="myimg" src="img1.jpg" hieght="300" width="300" onClick="change ()"/>
</body>
</html>
<html>
<head>
<script>
function change () {
  var img=document.getElementById("myimg");
  if (img.src === "img1")
    img.src="img2.jpg";
  else 
    img.src="img1.jpg";
}
</script>
</head>
</html>
-4

Source: https://habr.com/ru/post/1778673/


All Articles