【问题标题】:Determine width of <td> based on width <td> below?根据下面的宽度 <td> 确定 <td> 的宽度?
【发布时间】:2013-02-12 04:41:03
【问题描述】:

我想知道是否可以根据下面标签的宽度来确定标签的宽度。

我目前有这张桌子:

<table>
  <tr>
    <td>This title is way too long and screws up my style</td>
    <td>Title2</td>
    <td>Title 3</td>
  </tr>
  <tr>
    <td><img src="http://domain.com/image1.jpg" /></td>
    <td><img src="http://domain.com/image2.jpg" /></td>
    <td><img src="http://domain.com/image3.jpg" /></td>
  </tr>
</table>

是否可以根据下面图像的宽度来缩放标题标签?

希望清楚。

【问题讨论】:

  • 按比例是指减少font-size
  • 是否允许使用 JavaScript/jQuery(您没有将其添加到标签中)?
  • 您的目标是强制TD 元素的宽度仅与下方行中的IMG 元素一样宽吗?
  • 感谢您的回复。为了更清楚,图像是通过循环收集的。请参阅此以获得进一步说明(wordpress 功能):advancedcustomfields.com/resources/field-types/gallery 有没有办法通过循环收集每个图像的图像宽度?谢谢

标签: html css wordpress html-table


【解决方案1】:

这可能被认为是一个小技巧,但如果您将上一行中单元格的宽度设置为可接受的最小值,第二行中的单元格将扩展列。这是一个示例:

 <style>
     tr.titles td {
         width: 1px;
     }
 </style>

<table>
  <tr class="titles">
    <td>This title is way too long and screws up my style</td>
  </tr>
  <tr>
    <td><img src="http://domain.com/image2"/></td>
  </tr>
</table>

所以在这种情况下,将由图像决定列的宽度,并且总宽度将等于图像宽度。

【讨论】:

  • 感谢您的回复。这确实有效,但没有更好的方法来实现这一点吗?为了更清楚,图像是通过循环收集的。请参阅此以获得进一步说明(wordpress 功能):advancedcustomfields.com/resources/field-types/gallery 有没有办法通过循环收集每个图像的图像宽度?谢谢
  • 如果我理解正确的话,你关心的是 img 元素上的 style="width:100px" 。我认为您可以省略宽度并让浏览器自动处理。
  • 很好,你想让第一行 td 像第二行一样减小宽度吗?就是这样:删除第一个 td 宽度,让第二个 td 适合内部图像。
【解决方案2】:

我可以建议一种使用 jquery 的方法。 检查此代码:

如果这是你的表。给它一个 id。

<table id='mytable'>
  <tr>
    <td>This title is way too long and screws up my style</td>
    <td>Title2</td>
    <td>Title 3</td>
  </tr>
  <tr>
    <td><img src="http://domain.com/image1" /></td>
    <td><img src="http://domain.com/image2" /></td>
    <td><img src="http://domain.com/image3" /></td>
  </tr>
</table>

所以在脚本部分

<script>
$(document).ready(function () {
            $('#myTable > tr > td').click(function () {
                 var width = $(this).next('td').children('img').prop('width');
                 $(this).prop('width',''+width+'px');
            });
});
</script>

【讨论】:

  • 感谢您的回复。但是,它似乎不起作用。标题的 td 占用了必要的整个宽度....
  • 查看我在主题下的评论以进一步澄清我的问题。谢谢
  • 我已经添加了一些代码来获取图像。希望这有效。试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 2012-02-29
  • 2013-10-18
  • 2013-05-18
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多