javascript - 一个元素中可以水平和垂直放置多少个等宽字符?

标签 javascript jquery html css monospace

我试图找出一个元素中有多少个等宽字符(例如 div ),知道大小和 font-size .

例如,我期望的结果是:

{
   x: Math.floor(divWidth / fontSize)
 , y: Math.floor(divHeight / lineHeight)
}

但似乎它们不对:对于字体大小 50pxwidth: 100px ,预期答案为 2 ,但它是3 :

div {
    font-family: monospace;
    background: black;
    color: lightgreen;
    font-weight: bold;
    width: 100px;
    height: 100px;
    font-size: 50px;
}
<div>
123
123
</div>

对于上面的例子,答案应该是:

{
   x: 3 // 3 chars horizontally
 , y: 1 // 1 char vertically
}

如何自动计算这些值?

var $div = $("div");
var divSize = {
    w: $div.width()
  , h: $div.height()
};
var fontSize = parseInt($div.css("font-size"));

最佳答案

我构建了一个 jQuery 插件来执行此操作:

$.fn.textSize = function () {
    var $self = this;
    function getCharWidth() {
        var canvas = getCharWidth.canvas || (getCharWidth.canvas = $("<canvas>")[0])
          , context = canvas.getContext("2d")
          ;
        
        context.font = [$self.css('font-size'), $self.css('font-family')].join(' ');
        var metrics = context.measureText("3");
        return metrics.width;
    };

    var lineHeight = parseFloat(getComputedStyle($self[0]).lineHeight);
    return {
        x: Math.floor($self.width() / getCharWidth())
      , y: Math.floor($self.height() / lineHeight)
    };
};

alert(JSON.stringify($("div").textSize()));
div {
    font-family: monospace;
    background: black;
    color: lightgreen;
    font-weight: bold;
    width: 100px;
    height: 100px;
    font-size: 50px;
    line-height: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

关于javascript - 一个元素中可以水平和垂直放置多少个等宽字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28052244/

相关文章:

javascript - Bootstrap : Button appearance changes upon hover

javascript - 替换文本 javascript .append()

jquery - 删除所有其他行后删除标题行

javascript - 没有 JQuery UI 的拖放

html - 倾斜输入边框而不倾斜内部文本

JavaScript 扩展类

javascript - 理解 modenizer 包含函数

Jquery 使用 attr() 禁用输入

html - Nav 和 nav ul 给出不同的高度

html - 如何在较大文本的顶部对齐较小的文本