【问题标题】:How do I add a class to the parent of an element whose height is greater than it's width如何将类添加到高度大于宽度的元素的父级
【发布时间】:2019-07-20 02:02:46
【问题描述】:

在我正在处理的 Wordpress 网站上,我需要为所有肖像图像添加一个“高”类,以便它们具有填充。所有其他图像将获得“宽”类。图像的标题也需要包含在填充中,因此实际上是 <figure> 父元素,我需要将“高”类添加到,而不是 <img> 标记。所以我试图为所有<figure> 元素添加一个类,这些元素有一个高度大于宽度的子<img>

我的问题是,虽然 <img> 指定了高度和宽度,但 <figure> 只有高度,所以下面的代码会导致将“宽”类添加到所有图像中,正如我猜测的那样只是从 <figure> 元素中获取宽度,而没有与之比较的高度,而应该从 <img> 元素中获取高度和宽度。

jQuery(window).on('load', function() {
    jQuery('img').parent().addClass(function() {
        if (this.height > this.width) {
            return 'tall';
        } else {
            return 'wide';
        }
    });
});
</script>

如何更正我的代码以向所有包含高度大于宽度的&lt;img&gt; 元素的&lt;figure&gt; 元素添加“高”类?

【问题讨论】:

  • height 和 width 不是参考图像,它是父图像。
  • 谢谢,那么我如何使高度和宽度参考图像,并且仍然将类添加到父级?

标签: jquery html css wordpress


【解决方案1】:

您只需要在函数内再次.find() 图像,因为this 将指向父级。此外,如果页面上有多个图像,您可能需要将其包装在 .each() 循环中,以便在 img 的每个实例及其各自的父级上调用它。

jQuery('img').each(function(index, element) {
    jQuery(element).parent().addClass(function() {
            let img = jQuery(this).find('img');
            if (img.height() > img.width()) {
                return 'tall';
            } else {
                return 'wide';
            }
        });
});

注意:这会将 1:1 比例的图像标记为“宽”

编辑:

如果您使用的是each,这会更加高效和直接:

jQuery('img').each(function(index, element) {
    let img = jQuery(element);
    let width = img.width();
    let height = img.height();
    let cls = width > height ? 'wide':'tall';

    img.parent().addClass(cls);
});

【讨论】:

  • @NPC 欢迎,检查编辑,我刚刚意识到我最初的答案有点过于复杂
【解决方案2】:

您可以尝试以下代码。您必须在 . 下找到 img 的高度和宽度。

jQuery('figure img').each(function() {

    if(jQuery(this).height() > jQuery(this).width())
    {
        jQuery(this).parent().addClass('tall');
        }
    else{
        jQuery(this).parent().addClass('wide');

        }
    });

【讨论】:

    猜你喜欢
    • 2013-12-04
    • 2020-10-09
    • 2013-06-17
    • 2016-07-30
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多