我有一个包含代码示例(如 github 中的要点)的 div,它突出显示了语法。我还在代码示例的左上角添加了一个绝对定位的小 div,我想将其移动到不同的行。
您可以在提供的图片的左上角看到标记为 >
的 div。我希望能够将该指针移动到特定的代码行。
我尝试在 \n
上使用 split
并测量第一行字符的高度,并将该数字乘以我想去的索引但出于某种原因那有点不对劲。
这是我试过的一些代码:
//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">></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/