使用JQuery设置输入项的大小

时间:2012-11-29 22:07:51

标签: javascript jquery

有以下代码:

$(".translated").mouseenter(function(){
    if ($(this).hasClass("editable")){
        return;
    }
    var h=$(this).height();
    var w=$(this).width();
    $(this).empty();
    $("<input/>", {
        type: "text",
        height:h,
        width:w,
        value:$(this).text()
        }).appendTo(this);
    $(this).height(h);
    $(this).width(w);
    $(this).addClass("editable");
});

此代码从<div>容器中删除文本,并在其中插入<input>项。但问题是:尽管<input><div>的值很高,但新h项的高度仍大于w容器。我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要计算<input>元素的边框和填充占用多少额外空间,然后从容器<div>的高度中减去该空间。这将为您提供设置<input>元素所需的实际高度:

var h = $(this).height(); // The height of the container <div>
//...
var $newInput = $("<input/>", { type: "text", value:$(this).text()}).appendTo(this);
var fullHeight = newElem.outerHeight();
var innerHeight = newElem.height();
var paddingEtc = fullHeight - innerHeight;
$newInput.height(h - paddingEtc);

您可能必须遵循相同的方法来设置<input>的宽度。

你可以看到它在这里工作(目前只有高度):http://jsfiddle.net/XrGxx/