gpt4 book ai didi

javascript - 计算给定字符串的真实像素宽度

转载 作者:行者123 更新时间:2023-11-28 13:07:36 28 4
gpt4 key购买 nike

我想计算 span 元素中给定文本的宽度(以 px 为单位)。我在 Stackoverflow 中检查了几个答案。但是对我没有任何作用:(。我想弄清楚我做错了什么。这是jsFiddle link。这是代码:

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

var ts_name = $('span#ts_name');
var ts_name_text=ts_name.text().trim();
var ts_name_p_box_width = $('div#container-testset-name').innerWidth()-100;
var text_width = $(ts_name).textWidth();

我的 text_p_box_width 结果是 737px,text_width 是 715px。然而,从 Chrome 浏览器中的 html View 可以清楚地看出文本大小大于其容器。那么我的错误是什么?提前谢谢你。

P.S. If you need some clarification please leave as comment.

Edit: I saw similar answer of @LeeTaylor in other question. However it doesn't solve my problem. Because in my case text inside of span element. But in your case text inside of div. I can not change span's display property to block. So for my case this does not work. I tried to generate dynamically two elements using jQuery and try to fetch width. But it is 0. I found that since this dynamically created objects does not included to DOM tree and CSS not applied it will work.

`var ts_name=$('span#ts_name').text().trim();

var text_container = $(document.createElement('span')).html(ts_name).attr('id', 'input_text');
var block_container = $(document.createElement('div')).html(text_container).css({display:'block'});
block_container.css({width: '3000px'});

console.log($(block_container).find('span#input_text').width());
console.log($(block_container).find('span#input_text').outerWidth());
console.log($(block_container).find('span#input_text').innerWidth());

我这样做是因为我想使用您的解决方案,但它不起作用。那么你对此有什么想法吗?

SOLUTION: I figure out why my code is not working I just change only one value in css like this:

div#ts_designer>div#container-testset-name.c-group-inner-row span#ts_name 
{
position: absolute;
left: 100px;
right: 0;
top: 0px;
bottom: 0;
width: auto!important;
white-space: nowrap; /*This line added*/
}

这是更新的 jsFiddle link .

P.S. I will up vote your answers as reward to your answers. However I cannot accept one of them.

最佳答案

您是否尝试过使用 scrollWidth

这可能会做你想做的事:http://jsfiddle.net/eJMAD/

scrollWidth 在所有浏览器中的工作方式可能不同,所以也许其他人有更好的解决方案,对跨浏览器更友好。

关于javascript - 计算给定字符串的真实像素宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com