Onload 使输入大小适合文本长度

2024-03-17

我试图让 jQuery 测试 onLoad 输入框中文本的长度,并更改输入框的大小以适应。这是迄今为止我的代码尝试:

$("#emailSubject").attr('size', this.val().length);

我收到以下错误:

this.val 不是函数

我究竟做错了什么?

Update:现在我不再收到第一个错误,但长度显示为 0,尽管它不应该是这样。 (我正在使用警报来检查长度是多少)。为什么会发生这种情况?

Update:这是代码上下文:

$(
        function()
        {
            //works correctly   
            alert($("#emailSubject").val().length);
            //throws error
            $("#emailSubject").attr('size', ($(this).val().length)); 
        }
    )

新错误-长度在警报中正确显示,但我收到错误:

索引或大小为负值或大于允许的量。


As Alien Webguy said https://stackoverflow.com/questions/6819548/onload-fit-input-size-to-length-of-text/6819648#6819648, you're trying to call a jQuery function (val) on what's probably a raw DOM element or the window object (you haven't shown enough context for us to know what this is, but the error tells us it's not a jQuery instance) the document object (because that's what jQuery sets this to when calling your ready handler). (Your update clarified it.) So the first thing is to get the correct reference for the field and wrap it in a jQuery instance.

但单独来说,如果你设置size对于字符数,该字段几乎肯定会比您想要的大得多。那是因为size以统一的字符宽度工作。

相反,通常的做法是使用与输入元素具有相同字体系列、样式、大小、文本装饰等的页外元素来测量实际字符串。像这样的东西(实时复制 http://jsbin.com/ifuzop):

CSS:

#theField, #measure {
  font-family: serif;
  font-size: 12pt;
  font-style: normal;
}
#measure {
  position: absolute;
  left: -10000px;
  top: 0px;
}

HTML:

<input type='text' id='theField' value=''>
<span id="measure"></span>

JavaScript:

jQuery(function($) {
  var field;

  // Hook up some events for resizing
  field = $("#theField");
  field.bind("change keypress click keydown", function() {
    resizeIt(field);
  });

  // Resize on load
  resizeIt(field);

  // Function to do the work
  function resizeIt(field) {
    var measure = $("#measure");
    measure.text(field.val());
    field.css("width", (measure.width() + 16) + "px");
  }
});

请注意,我也在调整各种事件的大小;我怀疑那里的列表是否全面,但它给了你一个想法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Onload 使输入大小适合文本长度 的相关文章