[英]html table column width, fix width at time of page creation
如果在呈現頁面時有一種簡單的方法可以固定html表列的寬度。 我不想在代碼中指定列的像素或百分比寬度。 但是,一旦創建了頁面並根據表中的初始內容確定了寬度,即使單元格內容的大小發生了變化,我也不想改變寬度。
只是讓您了解我要做什么,如果我有一個單元格更改的內容(例如,從普通更改為粗體),例如說當我將鼠標懸停在行上時,列的大小就會更改。 這看起來很奇怪。
老實說,我不明白您對我的評論的回答,但無論如何我都會嘗試回答:-)
您可能需要的是將每個單元格的內容包裝在div
(或某些其他塊元素)中並設置其寬度。 那應該限制了單元格的擴大,但是,正如我在即時消息中暗示的那樣,更寬泛的內容將溢出,這看起來很丑陋。 但是,您並沒有真正指定您想要更廣泛的內容做什么...
<style type="text/css">
#the-table td .wrap {
overflow: hidden; /* try different values for different effects */
}
</style>
<script type="text/javascript">
$(function(){
$('#the-table th, #the-table td').wrapInner(function() {
return $("<div/>").css("width", $(this).width() + "px");
});
});
</script>
實時示例: http : //jsfiddle.net/Vx5Zq/
請注意,如何在懸停時截斷字母F。
我認為這應該可以解決問題(雖然未選中):
var w = $('#myTable td.leftCol').outerWidth();
$('#myTable td.leftCol').css({width: w+'px'});
[編輯]
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$("table td").each(
function() {
var w = $(this).outerWidth();
alert(w+'px');
w *= 2;
$(this).css({width: w+'px'});
alert(w+'px');
}
);
}
);
</script>
</head>
<body>
<table>
<tr>
<td>abc</td>
<td>def</td>
<td>ghi</td>
</tr>
</table>
</body>
</html>
當文本變為粗體時,為當前tds添加一些寬度將停止調整大小。
首先使用CSS將表格設置為固定渲染:
<style type="text/css">
#mytable{ table-layout: fixed; }
</style>
然后,您可以使用jquery向tds添加2px的寬度,如下所示:
<script type="text/javascript">
$(function(){
$('#mytable td').each(function(){
var $this = $(this) // cache this td
// set style to 2px wider
$this.css({ width: $this.outerWidth() + 2, height: $this.outerHeight() + 2 });
})
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.