将内联样式添加到可见的最后一个孩子

时间:2018-05-20 06:32:46

标签: jquery jquery-selectors

我正在使用:

$( ".scroll > *:visible:last" ).css( "margin-bottom", "0" );

定位所有可见的孩子并添加" margin-bottom:0" (内联)到最后一个可见的子节点,它会产生这个结果:

<div class="scroll">

    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <div style="margin-bottom: 0px;">
        <p>fsfdsfsdfsd</p>
    </div>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>

</div>

这是预期的并且可以正常运行直到课程&#34;滚动&#34;是最后一个可见的孩子,如下:

<div class="scroll">

    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <div class="scroll">
        <p>fsfdsfsdfsd</p>
    </div>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>

</div>

现在可以像这样添加内联样式:

<div class="scroll">

    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <div class="scroll">
        <p style="margin-bottom: 0px;">fsfdsfsdfsd</p>
    </div>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>

</div>

我想我会期待这个:

<div class="scroll">

    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <p>This is text...</p>
    <div class="scroll" style="margin-bottom: 0px;">
        <p style="margin-bottom: 0px;">fsfdsfsdfsd</p>
    </div>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>
    <p class="hide">This is text...</p>

</div>

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您应该使用last-of-type代替last

  

:last-of-type选择器匹配最后一个元素   特定类型的孩子,其父母。

&#13;
&#13;
$(".scroll > *:visible:last-of-type").css("margin-bottom", "0");
&#13;
.hide {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroll">

  <p>This is text...</p>
  <p>This is text...</p>
  <p>This is text...</p>
  <p>This is text...</p>
  <p>This is text...</p>
  <p>This is text...</p>
  <p>This is text...</p>
  <div class="scroll">
    <p>fsfdsfsdfsd</p>
  </div>
  <p class="hide">This is text...</p>
  <p class="hide">This is text...</p>
  <p class="hide">This is text...</p>

</div>
&#13;
&#13;
&#13;