我使用的是从顶部到span的距离来垂直定位插入符号,这很好,我使用的是字符串的索引乘以字母宽度来水平定位插入符号但有时有效,有时不。
以第二行为例,点击第一行&;this&;,它不能正常工作但是如果你点击最后一行&;this&;插入符号被正确定位。
我不明白为什么,这是不是意味着一个单间距字体有完全相同的每一个字母,我在这里看到10.1?这里有些不对劲,我不知道是什么。JsFiddle
let writeDiv = document.querySelector('#write');
let caret = document.querySelector('#caret')
writeDiv.addEventListener('click', (e) => {
if(e.target.tagName == 'SPAN'){
moveCaretOnClick(e)
}
})
function moveCaretOnClick(e) {
let y = window.getSelection().focusOffset * 10.1
caret.style = `left: ${y}px; top: ${e.target.offsetTop + 3}px`;
}
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
body, html{
margin: 0;
height: 100%;
width: 100%;
}
#write {
font-family: 'Roboto Mono';
height: 100%;
width: 100%;
background: #1f2227;
padding: 10px;
color: white;
box-sizing: border-box;
}
#caret{
height: 15px;
width: 3px;
background: #80ff00;
display: inline-block;
position: absolute;
}
.RowSpan{
width: 100%;
display: inline-block;
box-sizing: border-box;
height: 20px;
}
<div id='write'>
<span class='RowSpan'>This is some text</span>
<span class='RowSpan'>this is some text this</span>
</div>
<div id='caret'></div>
编辑:我猜我需要字母的精确尺寸,否则,当你沿着线走得更远时,距离会越来越大,因为每个字母都会相乘。如果你添加更多的文字,点击的距离会越来越远。
所以,要么以某种方式得到字母的精确尺寸,这总是一致的,要么找到其他方法。
有点尴尬,但我找到了解决方案,结果是我只需要在每个字母相乘之前将1
添加到focusOffset
,否则它基本上会跳过一个字母。我想是因为focusOffset
以0
开头
let writeDiv = document.querySelector('#write');
let caret = document.querySelector('#caret')
writeDiv.addEventListener('click', (e) => {
if(e.target.tagName == 'SPAN'){
moveCaretOnClick(e)
}
})
function moveCaretOnClick(e) {
let y = (window.getSelection().focusOffset + 1) * 9.6
caret.style = `left: ${y}px; top: ${e.target.offsetTop + 3}px`;
}
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
body{
margin: 0;
}
#write {
font-family: 'Roboto Mono';
height: 300px;
width: 1200px;
background: #1f2227;
padding: 10px;
color: white;
}
#caret{
height: 15px;
width: 2px;
background: #80ff00;
display: inline-block;
position: absolute;
}
.RowSpan{
width: 100%;
display: inline-block;
box-sizing: border-box;
height: 20px;
}
<div id='write'>
<span class='RowSpan'>This is some text</span>
<span class='RowSpan'>this is some text this more more text BIGGERT TEXT and some small text and some stuff -- __ !%^ () {} and some more text even </span>
</div>
<div id='caret'></div>