最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to limit entered text by pixel width, not character count - Stack Overflow

programmeradmin1浏览0评论

Given a fixed pixel width (text needs to fit on an 80px button; assume no padding), how can I limit the text a user enters into a text field to that limit (80px). If it helps, I know the font (Arial) and the font size (12pt).

The limit should be enforced real time (user should be able to delete and add text without submission).

For example, the text field should let the user enter 4 "W's" or 9 "I's" as long as it es in under the 80px.

Given a fixed pixel width (text needs to fit on an 80px button; assume no padding), how can I limit the text a user enters into a text field to that limit (80px). If it helps, I know the font (Arial) and the font size (12pt).

The limit should be enforced real time (user should be able to delete and add text without submission).

For example, the text field should let the user enter 4 "W's" or 9 "I's" as long as it es in under the 80px.

Share Improve this question asked Jun 3, 2015 at 15:25 Jon S.Jon S. 1131 silver badge7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You can use canvas to measure pixel-perfect widths. Just create a wrapper object to do the measuring (so you don't need to recreate the canvas each time):

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>

may be you need some thing like text.width()

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

I think that code will help you:

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

Just throwing out an idea here but, why not use a Monospace font? Since monospace font characters are all a fixed width, given a font size, some experimentation, and a little math later, you could use character count to limit the input to 80px.

发布评论

评论列表(0)

  1. 暂无评论