简体   繁体   中英

How to on img click, show just one, and hide other divs

I'm working on project, and got stuck with JS. Please before you read text, see the picture. Picture

I want to make a slider (And I did), and now when I click on a circle, I want to show content-box only with the same color, and others should be hidden.

eg when I click on .imgRed, I want only #red to be displayed, others, #blue and #black to be display: none; .

Thank you.

You probably know what you should do but you are not confident about it. You should hide others but the one that you want to stay present.
For example for red you should do:

$('.imgRed').click(function() {
    $('#red').show();
    $('#black').hide();
    $('#blue').hide();
}

and repeat for all of the others.

I tried to create a working snippet according to the image, where I used:

  • A class for the circles, another class for the bars,
  • The circles got a data-color attribute that will target the bar to be displayed on click.

Here it is:

 // When clicking a circle, use the data-colo to display the correct bar $('.circle').click(function() { $('.bar').hide(); var color = $(this).data('color'); $('#' + color).show(); }); // Trigger the click event on load: $('.imgRed').trigger('click'); 
 .circle { display: inline-block; margin: 8px 16px; border: 30px solid; border-radius: 50%; height: 0; width: 0; } .bar { display: none; margin: 8px 16px; height: 40px; width: 250px; } .imgRed { border-color: red; background-color: red; } .imgBlack { border-color: black; background-color: black; } .imgBlue { border-color: blue; background-color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="circle imgRed" data-color="red"></div> <div class="circle imgBlack" data-color="black"></div> <div class="circle imgBlue" data-color="blue"></div> <br><br> <div class="bar imgRed" id="red"></div> <div class="bar imgBlack" id="black"></div> <div class="bar imgBlue" id="blue"></div> 

Hope it helps.

$('.imgRed').click(function(){
    $('#red').show();
    $('#blue,#black').hide();
});

now when you click on all elements with class .imgRed only those with ID red will be visible.

the same you have to do with your other classes;

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