简体   繁体   中英

Anchor hidden div when button is clicked

I have three buttons all of which contain hidden content. When a button is clicked, I want that specific content to display and hide all other content. I also want the screen to jump down to the content that shows when clicking on the button.

What do I need to add to the JavaScript to make it jump down to the content? Here is what I have:

 $("#wrap div[id^='Template']").click(function() { var active = $(this).attr('id'); $(this).siblings("[class^='Template']:not(." + active + ")").hide(); $(this).siblings("." + active).slideToggle(); }); 
 #Template2, #Template3, #Template4 { margin-top: 24px; margin-left: 19% !important; background-color: #cb3778; padding: 0 30px 0 30px; font-family: Arial; font-size: 20px; line-height: 36px; float: left; color: #FFF; cursor: pointer; -webkit-border-radius: 8; -moz-border-radius: 8; border-radius: 8px; } .Template2, .Template3, .Template4 { display: none; clear: both; width: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div style="display: block;" id="wrap"> <div id="Template2">Sample 2</div> <div id="Template3">Sample 3</div> <div id="Template4">Sample 4</div> <div align="center" style="padding-top:40px;" class="Template2"> <br> <br> <br> <br> <br>sample demo txt two 2</div> <div align="center" style="padding-top:40px;" class="Template3"> <br> <br> <br> <br> <br>sample demo txt two 3</div> <div align="center" style="padding-top:40px;" class="Template4"> <br> <br> <br> <br> <br>sample demo txt two 4</div> </div> 

Try adding this to the end of the click function.

$("body, html").animate({
    scrollTop: $(this).siblings("." + active).position().top
});

How about using CSS :target pseudo-class. See: http://codepen.io/zvona/pen/YwdGrW

.content {
  visibility: hidden;  
}

.content:target {
  visibility: visible;
}

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