【问题标题】:Calculate the width of the string base on font size and font style根据字体大小和字体样式计算字符串的宽度
【发布时间】:2014-05-21 16:04:31
【问题描述】:

我正在尝试根据字体大小和字体样式确定字符串的宽度。
但我不知道该怎么做。我在google上找到了一个函数,我不太明白它是如何工作的。

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

我对此进行了测试,得到了一个输出,我可以得到字符串的宽度,但是如果我声明字体样式和大小呢?我不知道该怎么做。对这个有什么想法吗?

【问题讨论】:

标签: jquery html css fonts


【解决方案1】:

使用这个:

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
 return width;
};

来自this 主题。

【讨论】:

  • 我已经看到了,。但如果,。字体样式和字号由用户动态选择?
  • 每次改变大小时你调用函数?!
猜你喜欢
  • 2017-10-08
  • 2010-11-22
  • 1970-01-01
  • 2019-04-08
  • 2014-07-15
  • 2013-02-06
  • 2012-03-05
  • 1970-01-01
相关资源
最近更新 更多