2017-05-14 30 views
1

我想获得一个字符的宽度计算任何给定字符的字符串中的位置(以像素为单位)。我认为这很容易,因为我使用的是等宽字体,但是我遇到了问题。获取字符宽度在Javascript

我已经尝试了建议,this answer但这并不大型字符串的工作。精度太差,这意味着它的工作原理,我可以得到字符串中前几个字符的位置,但在10个字符之后,精度非常差,我得到的字符的位置离它实际上很远给出角色的位置。

我想什么做的就是一个字符的宽度,使我可以只写是这样的:

var charWidth = ???; 
var position = 5; // Shuold get the position of the fifth character in the string 
var calculatedPosition = charWidth * position; 
+0

遇到问题SUG孕育了一个解决方案,因为我不完全清楚你想做什么 - 是根据字符在字符串中的位置定位HTML元素的目标?或者在字符串的那一点插入一些东西? – Toby

+0

@Toby我试图在该位置放置另一个元素,是的。 – Halliom

+0

@RachelGallen链接问题的答案,我将创建一个带有字符串的隐藏div,然后用它来计算字符宽度。 – Halliom

回答

3

试试这个solution, developed by Ben Ripkens

CSS:

.textDimensionCalculation { 
    position: absolute; 
    visibility: hidden; 
    height: auto; 
    width: auto; 
    white-space: nowrap; 
} 

JS :

var calculateWordDimensions = function(text, classes, escape) { 
    classes = classes || []; 

    if (escape === undefined) { 
     escape = true; 
    } 

    classes.push('textDimensionCalculation'); 

    var div = document.createElement('div'); 
    div.setAttribute('class', classes.join(' ')); 

    if (escape) { 
     $(div).text(text); 
    } else { 
     div.innerHTML = text; 
    } 

    document.body.appendChild(div); 

    var dimensions = { 
     width : jQuery(div).outerWidth(), 
     height : jQuery(div).outerHeight() 
    }; 

    div.parentNode.removeChild(div); 

    return dimensions; 
}; 

在他的博客,他写道

有了这个小片段的帮助下,我们可以计算出文本这样一直也写:

var dimensions = calculateWordDimensions('42 is the answer!'); <!--obviously a hitchhikers guide fan, lol ---> 

console.log(dimensions.width); 
console.log(dimensions.height); 

alternate [jquery] solution 尺寸菲尔Freo

$.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(); 
}; 
+0

很明显,你不必写尺寸控制台..使用它们无论你需要什么calcs.但我认为他的评论很有趣! :) –

+0

谢谢!我试了一下,它似乎是完美的工作!非常感谢你的帮助。 – Halliom

+0

耶!乐意效劳... –