简体   繁体   中英

Click an Image to Reveal Content

I have searched an searched for answer to this question but can't seem to find an answer that works for me. What I'm wanting is an image that presents itself on the page as with a normal tag. I want the image to be clickable, and when it is clicked, some content will drop down below it for a description of the image, etc. Then, when the image is clicked again, it will hide the content.

My (beginner) javascript attempt looks like this:

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js">

$(window).load(function(){
$(".header").click(function () {

$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
    //execute this after slideToggle is done
    //change text of header based on visibility of content div
    $header.text(function () {
        //change text based on condition
        return $content.is(":visible") ? "Collapse" : "Expand";
    });
});  

The HTML is this:

    <div class="container">
<div class="header"><img src="Placeholders/placeholder.jpg" width="500" height="333"></div>
<div class="content" style="display: none;">
    The words should be here.
</div>

Any help would be appreciated, and I apologize if this has been answered elsewhere. I couldn't find it.

You need a separate script tag for your code. You can't reuse the one that's importing jQuery.

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
  // Your code
</script>

Try this html:

 <div class="container">
    <div class="header"><img src="Placeholders/placeholder.jpg" width="500" height="333"></div>
    <div class="content" style="height: 0px;overflow:hidden;">
        The words should be here.
    </div>

And this script:

$(document).ready(function(){
    $(".header").click(function () {

        if($(".content").height() === 0){
             $(".content").animate({height: "20px"}, 500);
        }else{
            $(".content").animate({height: "0px"}, 500);
        }

    });
})

On jsfiddle: https://jsfiddle.net/wef1o0b5/

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