简体   繁体   中英

Selecting child of previous parent jQuery

Lately I've been trying my hand at animation using CSS and jQuery, it went well, however, now I want to do a bit more. That is, once the user clicks information should show up on top of the image.

At the moment, I just have a few tags on which I perform the animations and class toggles.

My question is, I've thought about doing the following:

<div class= "singleImage">
    <img src.... class="actualImage">
    <p>text to put over the image</p>
</div>

This would be done per image which means that I'll have about 5 of them with different images.

However, I don't know how to go about selecting the previous element of class "actualImage".

Has anyone got any suggestions?

Thank you

Use the jQuery prev function. Example: Assume you want to select the image previous to the second image:

var foo = $(".singleImage").eq(1);
var bar = $(foo).prev().find('.actualImage');

Fiddle

尝试这个:

$('singleImage').children('.actualImage').prev();

I'm not sure why you are trying to select the previous element, but you could do something akin to this:

  • Bind a function to the click event for the element containing your image and caption.
    • Inside this function, toggle the caption.
    • Also, bind a click event handler to the body to detect clicks "off" the containing element.

HTML:

<a href="#" class="has-caption">
    <img src="http://placehold.it/300x300" />
    <span class="caption">This is a caption</span>
</a>

CSS:

a.has-caption { position: relative; }
a.has-caption .caption {
    background: rgba(0, 0, 0, .25);
    bottom: 0;
    color: #fff;
    display: none;
    height: 20px;
    left: 0;
    line-height: 20px;
    position: absolute;
    width: 100%;
}
a.has-caption img { vertical-align: bottom }

JavaScript

$('a.has-caption').on('click', function(e) {
    e.preventDefault(); e.stopPropagation();
    var self  = $(this)
      , tmpId = 'toggle-' + Date.now();
    self.addClass(tmpId);
    $('span.caption', self).toggle();
    $('body').one('click', function(e) {
        if (!$(event.target).closest('.' + tmpId).length) {
            $('span.caption', '.' + tmpId).hide();
            self.removeClass(tmpId);
        };
    });
});

http://jsfiddle.net/83s7W/

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