[英]get X and Y position of string character written in div or where it is break
I want X and Y coordinates of string character written in div tag or position where it is break or from which character it is break in small size div tag.我想要在 div 标签中写入的字符串字符的 X 和 Y 坐标,或者它在小尺寸 div 标签中断开的位置或从哪个字符断开。
I have a <div>
element with a contenteditable
attribute like <textarea>
with css attribute word-wrap:break word.我有一个带有
contenteditable
属性的<div>
元素,例如带有 css 属性 word-wrap:break word 的<textarea>
。 I want to know , from which letter text goes to next line (without new line , for constant text).我想知道,从哪个字母文本转到下一行(没有换行,对于常量文本)。 So can i get the letter where y position of the letter is changed ?
那么我可以得到字母 y 位置改变的字母吗? so that i can add new line after that letter to draw text with canvas.
这样我就可以在该字母后添加新行以使用画布绘制文本。
If you are using a font that has a common width and height for each letter, say monospace
at 16px (which I just worked to calculate), if you compare this to the width of your div
, you may use something like this:如果您使用的字体对每个字母都有相同的宽度和高度,请说 16px 的
monospace
(我刚刚计算过),如果您将其与div
的宽度进行比较,您可以使用以下内容:
HTML:
<div id="input" contenteditable="true" style="width: 100px; height: 100px; font-size: 16px; font-family: monospace; line-spacing: 0px; letter-spacing: 0px; border: 1px solid #bbbbbb">
Some Text Some Text Some Text Some Text Some Text Some Text.
</div>
JavaScript:
var input = document.getElementById("input");
function getXandY(index) {
var x = 0, y = 0;
var length = input.innerHTML.substring(0, index).length; // Get length between beginning of string and chosen index
x = (length % 10); // Get letter index on line
if(length < 100) {
y = Math.floor(length / 10);
} else {
y = length / 100;
}
// Only works for chars less than 1000;
return "X: " + x + " Y: " + y;
}
alert(getXandY(23));
在文本节点的子字符串上使用范围对象来收集 boundingRects: https : //developer.mozilla.org/en-US/docs/Web/API/Range/getBoundingClientRect
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.