我一直在玩这个游戏,似乎无法让它按我的意愿运行。
here是我的例子,
我有一个表格,通过单击用户输入时将其文本内容替换为输入,我可以对其进行编辑。失去焦点后,将删除输入,并将单元格内容(输入)替换为更新的文本。
所有这些都很棒,很棒。我的问题是在输入替换文本后,单元格会自动调整大小。
我已经将输入的宽度设置为100%,但这就是我能想到的(除了测量像元宽度并将其硬编码为该宽度之外,如果可能的话,我想避免这种情况。)
(有关HTML内容,请参见示例)
CSS假定表的ID为#tblListings
#tblListings {
width: 100%;
}
#tblListings thead {
background-color: #dedede;
}
#tblListings td, #tblListings th {
padding: 6px;
border: 1px solid #adadad;
border-bottom: none;
}
#tblListings tbody tr:nth-child(even) td {
background-color: #efefef;
}
#tblListings tbody tr:last-child td {
border-bottom: 1px solid #adadad;
}
#tblListings td input {
width: 100%;
border: none;
outline: none;
background-color: #ff0;
}
javascript,我想这可以通过CSS来实现,但是为了安全起见,我将其发布。
$("#tblListings tbody").on("click", "td", function(event) {
if (event.target.tagName === "INPUT") return;
var cell = $(this);
var input = $("<input>", {
type: "text",
value: cell.text(),
maxlength: 128
});
cell.empty().css("padding", 0).append(input);
input.focus();
input.on("blur", function() {
cell.css("padding", 6).text(this.value);
});
});
最佳答案
一种方法是将输入设置为绝对定位,但将原始内容保留在单元格中以保持宽度不变。在此处查看更新:http://jsfiddle.net/V6rsC/29/。
我所做的是将单元格设置为具有相对位置,以便在设置输入范围时,它将使用单元格而不是文档。我将输入的左,上,右和下设置为0px。宽度保持不变,因为内容仍在那儿,但是由于输入妨碍了我们,所以我们看不到它们。完成后,无论如何都将替换内容,所以知道一个人就知道其中的区别。
关于javascript - 阻止表格单元扩展,或将输入设置为表格单元的宽度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8289347/