简体   繁体   English

如何使用JavaScript和jQuery设置HTML表单元格宽度

[英]How to set HTML table cell width using JavaScript and jQuery

I have a HTML table like the below; 我有一个如下的HTML表格;

<table style="width: 100%">
<tr>
<td style="width: 30px">cell</td>
<td class="cell">cell</td>
<td class="cell">cellcell</td>
<td class="cell">cellcellcell</td>
<td class="cell">cellcellcellcell</td>
<td class="cell">cellcellcellcellcell</td>
<td class="cell">cellcellcellcellcellcell</td>
<td style="width: 30px">cell</td>
</tr>
</table>

The table is designed to stretch to screen (or a div having specific width). 桌子设计成可伸展至屏幕(或具有特定宽度的div)。 I want equal width for all cells having class="cell" and this works well when the character length of text in all cells having class="cell" are equal. 我希望所有具有class="cell"都具有相同的宽度,并且当所有具有class="cell"单元格中的文本字符长度相等时,这种方法效果很好。 But, I want to fix the cell width even if the character lengths of contents in class="cell" are different. 但是,即使class="cell"中内容的字符长度不同,我也想固定单元格宽度。

Also you can see that the first and last cells have fixed width, in pixels and others cell widths are to be calculated on the basis of percentage .. I want equal width for all cells (except first and last with fixed width in pixels). 您还可以看到第一个和最后一个像元具有固定的宽度(以像素为单位) ,其他像元的宽度应基于百分比来计算。我希望所有像元的宽度都相等(除了第一个和最后一个像元的固定宽度以像素为单位)。

I think this can be done using Javascript with the help of jQuery, by calculating the table cell widths on document ready, and then adding some function using on window resize and thereby calculating cell widths. 我认为可以通过在jQuery的帮助下使用Javascript来实现,方法是计算准备好文档时的表格单元格宽度,然后on window resize添加一些函数,从而计算单元格宽度。 The cell widths will be (tablewidth in px - 60px)/6 I am a beginner and I don't know much.. How can I do this using jQuery and (or) Javascript. 单元格的宽度为(tablewidth in px - 60px)/6我是一个初学者,我不太了解。如何使用jQuery和(或)Javascript做到这一点。

It will be very helpful if someone make me a fiddle.. 如果有人使我成为小提琴,这将非常有帮助。

You could just do that with CSS, by applying each td an equal percentage: 您可以使用CSS做到这一点,方法是将每个 td均等地应用:

 
 
 
  
  td{ width: 16%; }
 
  

example: http://jsfiddle.net/niklasvh/wKmxD/ 例如: http//jsfiddle.net/niklasvh/wKmxD/

With your updated question, you could do it with javascript by first storing the widths into an array, and then referencing that on window resize , and use the aspect ratio difference to place new widths: 对于更新的问题,您可以使用javascript做到这一点,方法是先将宽度存储到数组中,然后在window resize上引用该宽度,然后使用宽高比差异放置新的宽度:

var w = [];
var tw = $('table').width();
$('table td').width(function(i,e){
    w[i]=e;
});

$(window).resize(function(){
    $('table td').width(function(i){
    return ($('table').width()/tw)*w[i];
    });
});

http://jsfiddle.net/niklasvh/543D9/ http://jsfiddle.net/niklasvh/543D9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM