以下は、 https://stackoverflow.com/a/5047712/212869からの回答を使用してテキストの幅を計算し、それをテキストボックスにリンクしました。その本当に大まかなコード:Dですが、テキストボックスをかなりうまく制限します. テキスト領域でも同じ原則を使用できますが、高さと幅の両方でも同じことを行う必要があります。
http://jsfiddle.net/LMKtd/1/ - コンソールに何かを出力するので、見ている場合は開いておくのが最善です。
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}
アップデート
http://jsfiddle.net/LMKtd/8/
テキスト領域にも 1 つをまとめました。制限を超えるのを止めることはありませんが、幅が広すぎたり高すぎたりすると通知されます。それはあまりきれいではありません:D
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'visible', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
String.prototype.height = function(font) {
var f = font || '12px arial',
o = $('<div>' + this.replace(/[\r\n]/g,'<br />') + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.height();
o.remove();
return w;
}
$('#textinput').on('keyup', validatetext);
$('#areainput').keyup(validatearea);
function validatearea(e) {
var w = parseInt($(this).val().width());
var h = parseInt($(this).val().height());
var errw = false;
var errh = false;
if (h>100) {
errh = true
}
var lines = $(this).val().split(/[\r\n]/);
var errw = false;
for (var i = 0; i<lines.length; i++) {
if (parseInt(lines[i].width()) > 100) {
errw = true;
}
}
if ((errh == true) || (errw == true)) {
if ((errh == true) && (errw == false)) {
$('#areaerror').html("Too Tall, Width OK");
}
if ((errh == false) && (errw == true)) {
$('#areaerror').html("Height OK, Too Wide");
}
if ((errh == true) && (errw == true)) {
$('#areaerror').html("Too Tall, Too Wide");
}
} else {
$('#areaerror').html("Were Good");
}
}
function validatetext(e) {
var w = parseInt(e.target.value.width());
if (w > 100) {
console.log("Width Gt 100px ["+w+"px] Char Count ["+e.target.value.length+"]");
do {
e.target.value = e.target.value.slice(0,-1);
} while (parseInt(e.target.value.width()) > 100)
} else {
console.log("Keep going! ["+w+"px] Char Count ["+e.target.value.length+"]");
}
}