如何限制输入文本的像素宽度,而不是字符数

How to limit entered text by pixel width, not character count

本文关键字:字符 输入 何限制 文本 像素      更新时间:2023-09-26

给定一个固定的像素宽度(文本需要适合80px的按钮;假设没有填充),我如何限制用户输入文本字段的文本到该限制(80px)。如果有帮助的话,我知道字体(Arial)和字体大小(12pt)。

限制应该实时执行(用户应该能够在不提交的情况下删除和添加文本)。

例如,文本框应该允许用户输入4个"W"或9个"I",只要它在80px以下。

您可以使用canvas来测量像素完美的宽度。只需创建一个包装器对象来进行测量(这样您就不需要每次都重新创建画布):

function Measure(font) {
  this.canvas = document.createElement("canvas");
  this.ctx = this.canvas.getContext("2d");
  this.ctx.font = font;
  // method to call to measure width in pixels
  this.getWidth = function(txt) {
    return this.ctx.measureText(txt).width
  };
}
// set up a global instance
var m = new Measure("12pt sans-serif");
// get funky
document.querySelector("input").onkeyup = function() {
  var w = Math.ceil(m.getWidth(this.value)); // round up in case of float
  document.querySelector("span").innerHTML = w;
};
<input style="font:12pt sans-serif"> <span>0</span>

也许你需要一些类似text.width()的东西

var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px";

我想这段代码会对你有帮助:

#id {
    width: ;
    height: ;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

只是抛出一个想法,但是,为什么不使用统一字体?由于等宽字体字符都是固定宽度,给定字体大小,进行一些实验,然后进行一些数学计算,您可以使用字符计数将输入限制为80px。