javascript - 找到元素中每行的 y 位置?

标签 javascript jquery html css

我有一个包含代码示例(如 github 中的要点)的 div,它突出显示了语法。我还在代码示例的左上角添加了一个绝对定位的小 div,我想将其移动到不同的行。

您可以在提供的图片的左上角看到标记为 > 的 div。我希望能够将该指针移动到特定的代码行。

我尝试在 \n 上使用 split 并测量第一行字符的高度,并将该数字乘以我想去的索引但出于某种原因那有点不对劲。

enter image description here

这是我试过的一些代码:

//The code in a pre.. the {{}} is my template code. 
<pre class="code-view" data-id="{{ file.id }}"><code>{{ file.content }}</code></pre>
//The pointer
<div id="pointer">&gt;</div>
//move the pointer to the top left corner of the code sample
$("#pointer").css("left",$("pre.code-view:visible").first().position().left)
$("#pointer").css("top",$("pre.code-view:visible").first().position().top)

//this logs to 15
var c = 0;
var lineHeight = $("span.hljs-comment:visible").first().height();
    //I have multiple pre's on the screen. Only first one is visible.
var codeTop = $("pre.code-view:visible").first().position().top;
function moveToNextLine(){
    c++
    console.log(c,lineHeight,codeTop)
    $("#pointer").css("top",codeTop + (lineHeight * c));
};
moveToNextLine()
moveToNextLine()
moveToNextLine()

最佳答案

我最后做的是用 \n 换行符拆分 div 的文本。然后我用 class="code-line" 将每个换行符包装在一个范围内。这样我就可以得到每行代码在 div 中的位置。

关于javascript - 找到元素中每行的 y 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473095/

相关文章:

javascript - Ajax Form提交后需要清空

javascript - 使用 javascript 对 1 个输入进行多重验证

javascript - 为什么 Firebug 说 $.cookie() 不是函数?

javascript - 如何根据分隔符从字符串创建循环

php - Laravel 5.3 中的搜索栏以过滤表格

html - 为什么 TD 没有按预期扩展?

javascript - 在发送到服务器之前在 JS 中准备对象?

javascript - 调用从 Ajax 响应返回的 JavaScript 函数

javascript - 如何设置事件点击完整日历以便您进入该事件的编辑页面?

javascript - 如何在 JQuery 中通过属性查找元素?