Css动态设置数组中元素的大小

Css set size of elements in array dynamically

本文关键字:元素 动态 设置 数组 Css      更新时间:2023-09-26

我有一个元素数组,它们的标签class='element'。如何动态设置每个元素加载时的高度?当我试图设置

$('.element').css('height',sizeOfContent+'px');

它改变了每个。element的高度

从字面上理解你的问题,并根据你有限的标记给出一个想法:

jsFiddle DEMO

<div id="box1" class="element"></div>
<div id="box2" class="element"></div>
<div id="box3" class="element"></div>
CSS

.element {
  width: 50px;
  height: 50px;
  float: left;
  margin: 20px;
  border: 3px dashed black;
}
#box1 {
  background-color: red;
}
#box2 {
  background-color: blue;
}
#box3 {
  background-color: green;
}

JS

$(document).ready(function() {
    // Grab all elements on the page with classname '.element'
    var myElements = $('.element');
    // These are the sizes we need to change dynamically.
    // As seen in jsFiddle CSS panel, the original height for the above classname is 50px;
    var sizeOfContent = [ "100", "200", "300"];
    // Here, we run a .each() iteration and use the zero indexed value to match the corrisponding height as provided in variable sizeOfContent.
    $(myElements).each(function(index) {
        // Activate the console.log to view results in the browers console.
        //console.log( this );
        // jQuery css will automatically use pixle value when not specified
        $(this).css('height', sizeOfContent[index]);
    });
});

我想这可能是你想要做的?将每个.element设置为特定的高度?sizOfContent将以这种方式为每个元素设置,您没有提供如何设置sizOfContent的代码-所以我把它放在这里的注释中

$.each('.element' , function(){
   var sizeOfContent = // dynamically set sizOfContent
// maybe something like this..
// var sizOfContent = $(this).parent().height();
// ** you wouldn't need an each loop just set to parents height, but you see how it can be dynamically set    
   $(this).css('height',sizeOfContent+'px');
});

问题是$('.element')正在捕捉该类的所有元素。这就是它的作用。你需要一个唯一的标识符,例如$('#element1'),但是因为你没有告诉我们任何关于这些元素是如何创建的,sizeOfContent是什么或者它是如何派生的,所以不可能在代码中提供解决方案,所以这里是文字。

我只能假设你在迭代你提到的数组,所以

如果你正在创建对象并附加到页面,将.css('height',sizeOfContent+'px');添加到jQuery链中,如.appendTo('body')将存在或给它们每个ID并使用$('#element' + i).css('height',sizeOfContent+'px');

$.each(thearray, function(i,data){ // or perhaps for (i in thearray) {
    var sizeOfContent= some formula;
    div=$('<div class="element">').appendTo('#somewrapper').css('height',sizeOfContent+'px');
});

信息这么少,不可能回答。