JQuery只改变第一个实例

时间:2015-10-07 22:36:50

标签: jquery

我有一些代码可以找到类名为.tab-content-header的div的高度,然后更改该div内部h1的line-height。它适用于.tab-content-header h1的第一个实例,但我有几个实例,并希望同时更改所有实例的行高。所有这些都应该是一样的。我怎样才能改变我的代码来实现这个目标?我尝试使用.each(),但事情变得混乱而且无法正常工作。下面是我目前拥有的JQuery和.tab-content-header h1的一个实例,因此您可以看到标记的样子。

$(window).resize(function() {
    var $tabContentHeader = $('.tab-content-header');
    var $headerLineHeight = $tabContentHeader.height() + 10 + 'px';
    $tabContentHeader.find('h1').css({'line-height': $headerLineHeight});
});

<div class="row tab-content-header">
    <img src="images/content-area/page-header.png" class="img-responsive" alt="a1">
    <h1>Welcome</h1>
</div>

2 个答案:

答案 0 :(得分:0)

这是一份工作副本

http://jsfiddle.net/m330147x/1/

$(window).resize(function() {
    console.log("Start");
    var $tabContentHeader = $('.tab-content-header');
    console.log("Found " + $tabContentHeader.length + " Headers");

    var $headerLineHeight = $tabContentHeader.height() + 10 + 'px';

    var $h1 = $tabContentHeader.find('h1');
    console.log("Found " + $tabContentHeader.length + " h1");
    $h1.css({'line-height': $headerLineHeight});
    console.log("Finish");
});

查看开发人员控制台以获取调试信息。它应该工作得很好。

答案 1 :(得分:0)

使用此功能。

$(window).resize(function() {
    $('.tab-content-header > h1').each(function(i, obj) {
        var headerHeight =  $('.tab-content-header').height() + 10;
        obj.style.lineHeight = headerHeight + "px";
    });
});

参见工作示例:https://jsfiddle.net/g73uv468/

相关问题