【问题标题】:Css set size of elements in array dynamically [closed]Css动态设置数组中元素的大小[关闭]
【发布时间】:2013-01-04 19:06:48
【问题描述】:

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

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

它改变每个 .element 的高度

【问题讨论】:

  • sizeOfContent 的代码在哪里?
  • 你能再解释一下你想做什么,因为你说你想做的就是你看起来在做什么
  • 你试过这个CSSheight:auto;吗?
  • 你一直回复 cmets ,但没有添加任何代码
  • 不设置高度怎么办?这有什么问题吗?

标签: javascript jquery html css


【解决方案1】:

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

jsFiddle DEMO

HTML

<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]);

    });

});

【讨论】:

    【解决方案2】:

    我认为这可能是您想要做的?将每个.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');
    });
    

    【讨论】:

      【解决方案3】:

      问题是$('.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');
      });
      

      信息太少,无法回答。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-21
        • 2021-12-25
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多