简体   繁体   English

选择上一个父级jQuery的子级

[英]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. 最近,我一直在尝试使用CSS和jQuery制作动画,但是效果很好,但是,现在我想做的更多。 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. 这将针对每个图像进行,这意味着我将有大约5个具有不同图像的图像。

However, I don't know how to go about selecting the previous element of class "actualImage". 但是,我不知道如何选择类“ actualImage”的上一个元素。

Has anyone got any suggestions? 有没有人有任何建议?

Thank you 谢谢

Use the jQuery prev function. 使用jQuery prev函数。 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. 将函数绑定到包含图像和标题的元素的click事件。
    • Inside this function, toggle the caption. 在此功能内,切换标题。
    • Also, bind a click event handler to the body to detect clicks "off" the containing element. 同样,将click事件处理程序绑定到主体以检测单击“关闭”包含元素的情况。

HTML: HTML:

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

CSS: 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 的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/ http://jsfiddle.net/83s7W/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM