Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

javascript - Detect if text in an input (type=text) element exceeds bounds in FireFox

Is there a way to detect if the content (value) of an input (type=text) element exceeds its size?

In Internet Explorer, the scrollWidth property will be larger than style.width when this is true. In Firefox however, scrollWidth always equals style.width and is a known bug ( https://bugzilla.mozilla.org/show_bug.cgi?id=343143 ), well maybe not bug because Mozilla simply doesn't consider an input element to be "scrollable", but still. In line with this opinion, Firefox's textarea element DOES properly set the scrollWidth property when the content overflows the bounds.

Currently, my only thoughts are to either: (a) Use a textarea element instead and limit it to single line input somehow or (b) On each keyup event of the input, copy the contents to a similarly shaped div element and look at its scrollWidth property.

Is there a better way to accomplish this in FF?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

what if you measure the string's length in pixels? then you could compare the input's width with it.
Here is how you can get the pixel length of a string with jquery : Determine Pixel Length of String in Javascript/jQuery? .
I would do something like :

function inputExceeded(el){
    var s = $('<span >'+el.val()+'</span>');
    s.css({
       position : 'absolute',
       left : -9999,
       top : -9999,
       // ensure that the span has same font properties as the element
       'font-family' : el.css('font-family'),
       'font-size' : el.css('font-size'),
       'font-weight' : el.css('font-weight'),
       'font-style' : el.css('font-style')
    });
    $('body').append(s);
    var result = s.width() > el.width();
    //remove the newly created span
    s.remove();
    return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...