【问题标题】:jQuery - Run function on each <li> of UnsliderjQuery - 在 Unslider 的每个 <li> 上运行函数
【发布时间】:2018-03-29 20:18:57
【问题描述】:

我正在使用Unslider,滑块工作正常。
我在每个 &lt;li&gt;&lt;h1&gt; 中都有作为幻灯片的标题。
我有一个 resizeH1() 函数来调整这个&lt;h1&gt;

    function resizeH1() {
    var $h1 = $('.entry-header h1');
    if (window.innerWidth >= 768) {

        // Calculate the total height of the element
        var totalHeight = ($h1.height());

        var numOfLines = totalHeight / 88;
        // Force this element height to always be 88px
        $h1.height(88);
        // Adjust $h1 font-size depending on it's number of lines
        if (numOfLines === 2) {
            $h1.css('font-size', '42px');
        } else if (numOfLines === 3) {
            $h1.css('font-size', '40px');
        } else if (numOfLines === 4) {
            $h1.css('font-size', '38px');
        } else if (numOfLines >= 5) {
            $h1.css('font-size', '28px');
        }
        // Align the $h1 text verticaly at the very end
        if (numOfLines >= 2) {
            $h1.css({
                'text-align': 'center',
                'display': 'flex',
                'justify-content': 'center',
                'align-items': 'flex-end'
            });
        }
    } else {
        // Reset the $h1 state when (window.innerWidth < 768)
        $h1.css({
            'height': '',
            'font-size': '',
            'text-align': '',
            'display': '',
            'justify-content': '',
            'align-items': ''
        });
    }
}

我的问题是这个函数只适用于第一个&lt;h1&gt;的第一个&lt;li&gt;
和其他&lt;h1&gt; 的其他&lt;li&gt; 得到相同的font-size 作为第一个!

如何在每个&lt;li&gt; 上运行resizeH1() 而不仅仅是第一个?
在发布之前,我已经尝试了我所知道的所有内容并进行了很多搜索。
非常感谢您的任何建议/帮助。

【问题讨论】:

标签: jquery css unslider


【解决方案1】:

你需要一个循环结构。对于 jQuery 元素,您可以使用 .each()。您的代码如下所示:

function resizeH1() {
    $('.entry-header h1').each(function () {
        $h1 = $(this);
        if (window.innerWidth >= 768) {
            // Calculate the total height of the element
            var totalHeight = ($h1.height());

            var numOfLines = totalHeight / 88;
            // Force this element height to always be 88px
            $h1.height(88);

            (...)
        }
    });

欲了解更多信息,请参阅api.jquery.com/each/

【讨论】:

  • 非常感谢@kautella。我觉得很愚蠢 :( 我正在做相反的事情,针对 .each() .entry-header h1 然后调用 resizeH1() 而不是直接循环函数本身......
猜你喜欢
  • 2020-02-22
  • 2012-11-27
  • 2016-12-24
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2011-09-18
相关资源
最近更新 更多