在元素上的OnLoad

时间:2019-01-21 15:28:27

标签: javascript jquery html css

假设作为练习,我们必须将div height动态调整为前一个div之一。

我的问题是如何将其应用到元素的“ onload”上,以使每个div的单个上一个元素...

假设代码

$(".description").css("height", 
                      $(".description").prev(".pic").height());
.pic {float: left; width: 50%; border: 1px solid red;}
.description {border: 1px dotted green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <figure>
    <div class="pic">pic1<br>this is a big pic</div>
    <div class="description">one is OK</div>
  </figure>
  <figure>
    <div class="pic">pic2<br>this<br> is a pic2<br>this is another big pic</div>
    <div class="description">two is NOK</div>
  </figure>
  <figure>
  etc...
  </figure>
</div>

您会看到,该代码仅适用于第一个description,第二个描述仍调整为第一个。

PS。

不要提议重新格式化HTML ,我想知道如何为特定的HTML元素应用一些JS代码: 类似于在div上“加载”的东西元素,以正确识别前一个元素

2 个答案:

答案 0 :(得分:3)

您可以利用.css()可以传递函数的事实:

$(".description").css("height", function() {
  var element = this; // current "description" element
  return $(element).prev(".pic").height() + "px";
});

回调函数中this的值将依次是与选择器(".description")匹配的每个元素。

答案 1 :(得分:1)

此代码可以完成,您需要遍历所有.pics

$(document).ready(function() {
  $(".description").each(function(){
    var height = $(this).parent().find('.pic').height();
    $(this).css('height',height);
  })
});
相关问题