javascript - 在这种情况下,为什么自定义插入符号不能始终正确定位?
问题描述
我正在使用从顶部跨度的距离来垂直定位插入符号,这工作正常,我使用字符串的索引乘以字母宽度来水平定位插入符号,但有时有效,有时它没有吨。
例如查看第二行,然后单击第一个“this”,它无法正常工作,但如果您在最后一个“this”内单击,插入符号会正确定位。
我不知道为什么,这是否意味着单空间字体与我在这里目测为 10.1 的每个字母完全相同?有些东西在这里不起作用,我不知道是什么。提琴手
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>
推荐阅读
- python - 没有事先定义变量时,如何在 Python 中编写函数?
- date - 如何验证 ocl 中的 java.util.Date 属性?
- ruby-on-rails - 对活动模型序列化器属性的嵌套查询
- java - 从Android中的JSONObject中提取元素
- reactjs - 单击注销按钮时出现内存泄漏错误
- neo4j - 如何添加到属性的字符串值而不是在 Cypher Neo4J 中重写它?
- typescript - 使用实体存储库的全局实例在事务中保存多个对象(TypeORM)是否安全?
- r - 基于子类对 2 个匹配的队列进行重塑,然后进行连续的 McNemar 测试
- javascript - web api和接口有什么区别?
- postgresql - flyway 后的 Flyway 迁移错误:基线