问题描述:

I have two image div in HTML i want that onclik of one image other image should change

 <div class="image_21"><img src="pagetwo_graph_two_4.png"/></div>

<div class="alignment"><img src="pagetwo_graph_one.png"/></div>

<div class="image_one"><img src="pagetwo_graph_two_1.png"/></div>

<div class="image_two"><img src="pagetwo_graph_two_2.png"/></div>

<div class="option_image"><img src="option1.png"/></div>

<div class="option_image_label">Option 1</div>

<div class="option_image_one"><img src="option1.png"/></div>

<div class="option_image_label_one">Option 2</div>

I want that on click on option_image_one it should change image of image_one and imagetwo

网友答案:

UPDATE

<html>
 <head>
  <script type="text/javascript">
   function changeImage(){
    document.getElementById('toChange').src='3.jpg';
   }
  </script>
 </head>
 <body>
  <div class="option_image_one"><img src="1.jpg" onclick="changeImage()"/></div>
  <div class="image_two"><img src="2.jpg" id="toChange"/></div>
 </body>
</html>

Here the code that works for me

网友答案:

Best option is to give images some id and then do something like document.getElementById('yourId').src='newimage' (this should be some js function that you assign to onClick event on your first div)

网友答案:
onclick = "document.getElementById('option_image_one').getElementsByTagName('img')[0].src='pagetwo_graph_two_2.png' "

It would work.

网友答案:

You can try the following:

 <div class="option_image_one">
  <img onclick="document.getElementById('image2').src='http://www.w3schools.com/images/compatible_firefox.gif'" src="http://www.w3schools.com/images/compatible_chrome.gif"/>
 </div>
 <div class="image_two">
  <img id="image2" src="http://www.w3schools.com/images/compatible_safari.gif"/>
 </div>

Note that I have added an ID to the second image.

See the live example on this interactive HTML/JS editor

网友答案:

div are useless

<img src="option1.png" id="img1" onclick="document.getElementById('img2').src='newImage.png'"/>
<img src="pagetwo_graph_two_2.png" id="img2"/>
网友答案:

If you could use jQuery it would be like this:

$(".option_image_one img").onclick(function(event) {
    $(".image_two img").attr('href','different_image,jpg').hide().fadeIn("fast");
});

To use jQuery import the jQuery library by including the following in your header:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
网友答案:

As per Thomas's and Filype's answers, I would suggest that use divs but put onClick for img tag and not div tag.

This is for future enhancement so that if you would like to add anything else to these divs.

相关阅读:
Top