简体   繁体   中英

fading in and out an image using javascript

I have the code right so that when I click the image link jquery puts the image where it should be and at the proper size. However, I can't figure out what code to use in the javascript so that when I click the image again. It removes the current content from the div and puts it back in again instead of repeatedly putting the image in the div?

Here is the javascript code:

<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('img').click (function() { 
        $('.deal_content').append('<img src="deal_content.fw.png" width="700px" height="500px" alt="Deals" />');
        return false;   
    $('img').fadeToggle([normal]); 
    });
});
</script> 

Here is the HTML it is effecting:

<div class="deal_content">

</div>
<div id="content">
    <div id="imagelink"> 
        <a href="#">
            <img src="for_men_btn.fw.png" width="200" height="87" alt="For Men" />
        </a>
        <a href="#">
            <img src="for_couples_btn.fw.png" width="200" height="87" alt="For Couples" />
        </a>    
        <a href="#">
            <img src="for_teens_btn.fw.png" width="200" height="87" alt="For Teens" />
        </a>
    </p>

</div>

A simple if should be able to detect if there's already an image inside your element:

<script type="text/javascript">
$(document).ready(function() {
    $('img').click (function() { 
        if ($('.deal_content img').length > 0) {
            $('.deal_content img').remove();
        } else {
            $('.deal_content').append('<img src="deal_content.fw.png" width="700px" height="500px" alt="Deals" />');
        }
        return false;   
        $('img').fadeToggle([normal]); 
    });
});
</script> 

The following fade toggles the current clicked image. In this case you need to use a delegated event (see documentation ) to make it work on images that are appended dynamically.

$(document).ready(function() {
    $('.deal_content').on("click", "img", function() { 
        $(this).fadeToggle("normal"); 
    });
});

Then add a separate event handler for your link to append the images:

$('#imagelink a').click(function() { 
     $('.deal_content').append('<img src="deal_content.fw.png" width="700px" height="500px" alt="Deals" />');
    return false;
});

Not sure if this is what you are asking for?

$(document).ready(function() {
    $('img').click (function() { 
        var image = ('<img src="deal_content.fw.png" width="700px" height="500px" alt="Deals" />')
        $('.deal_content').html(image).hide().fadeToggle();   
    });
});

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