检测输入(type = text)元素中的文本是否超出了FireFox中的边界 [英] Detect if text in an input (type=text) element exceeds bounds in FireFox

查看:109
本文介绍了检测输入(type = text)元素中的文本是否超出了FireFox中的边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测输入(type = text)元素的内容(值)是否超出其大小?



在Internet Explorer中,<$如果是这样,c $ c> scrollWidth 属性将大于 style.width 。然而,在Firefox中, scrollWidth 始终等于 style.width 并且是一个已知的错误( https://bugzilla.mozilla.org/show_bug.cgi?id=343143 ),也许不是bug,因为Mozilla只是不认为输入元素是可滚动,但仍然。根据这个意见,当内容溢出边界时,Firefox的 textarea 元素可以正确设置 scrollWidth 属性。 p>

目前,我唯一的想法是:
(a)使用textarea元素,并将其限制为单行输入

(b)在输入的每个keyup事件中,将内容复制到类似形状的div元素,并查看其 scrollWidth 属性。



有没有更好的方式来完成这个在FF?

解决方案

如果您测量字符串的长度(以像素为单位),该怎么办?那么你可以比较输入的宽度。

这里是如何使用jquery获取字符串的像素长度:

我将执行以下操作:

 
函数inputExceeded(el){
var s = $('< span>'+ el.val()+'< / span> ;');
s.css({
position:'absolute',
left:-9999,
top:-9999,
//确保span的字体相同属性作为元素
'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();
//删除新创建的跨度
s.remove();
返回结果;
}


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?

解决方案

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;
}

这篇关于检测输入(type = text)元素中的文本是否超出了FireFox中的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆