将 offsetTop 与 AngularJS ng-repeat 一起使用

using offsetTop with AngularJS ng-repeat

我正在使用 ng-repeat 通过将单个字母重复到 span 元素中来输出段落。

<p><span>h</span><span>i</span><span> </span><span>M</span><span>s</span></p>

这些字母的内容跨度会在段落中多行。

line one of letters
even more letters here
and a few more

我的最终目标是能够检测出哪些跨度在哪一行上,以便为它们设置不同的样式。

我的想法是使用每个跨度的 offsetTop 值来检测不同的行。所以,在上面的答案中,我会有三个不同的 offsetTop

我在创建执行此操作的指令时遇到了一些问题 (运行 (based on this question)。发生了什么事,我得到了更多 offsetTop 应该在同一行的值。

Here's a Code Pen of me working through this problem in Angular.

Just to prove to myself that this could be done, I did it without Angular here.

在这些笔中,我正在控制台记录 top 值,并且顶部应该与线条一样多。

这是我第一次(真正)制定指令,所以我想知道我是否没有正确使用 element

任何方向都会有所帮助,感谢您的帮助!

你在没有 Angular 的情况下如何做的一个很大的区别是你是 运行 一切都呈现后的逻辑,但是 Angular 指令在每个跨越 span 被渲染的那一刻。我相信这就是为什么您看到顶部不断给您不同的值。

如果您向指令添加超时,它将等到 DOM 在 运行 超时内的函数之前完成渲染。

myApp.directive('positioner', function($timeout) {
return {
  restrict: 'A',
  link: function($scope, element){

    $timeout(function(){
        var top = element[0].offsetTop;
        var height = element[0].offsetHeight;

        console.log(top);
    }, 0);
  }
};

仅使用这个零超时给了我 3 个不同的最高值。