有没有办法动态地将元素添加到与另一个选定元素相同的高度?

时间:2014-07-07 23:33:16

标签: javascript html css zurb-foundation

我是前端开发的新手。我试图编写注释工具。示例屏幕显示在下图中。在用户选择句子之后,在右侧栏上出现与突出显示的句子相同的水平位置的注释框。关于如何实现这种效果的任何想法?

enter image description here

这是我的html结构。我使用了Zurb Foundation的框架:

  <section id="main">
        <div class="row">
            <div class="small-8 large-8 columns"id="rawdata">

                <p> <span class="sentence">2:22 So, last time I was here, I don't know if I told you this, but, um, we kind of did a "I like, I wish" activity on paper, about things that you like about studio, and things that you wish would change.</span><span class="sentence"> Um, do you want to share any of those thoughts now, so maybe we can talk about them? [name], I have yours if you want to look at it again.</span></p>
                <p><span class="sentence">2:47 I forgot to add something.</span></p>
                <p><span class="sentence">2:54 Well, I don't know, in terms of what I dislike about studio.</span></p>
                <p><span class="sentence">2:57 So, some people wrote in theirs that, um, they dislike how cluttered it gets.</span></p>

                <p><span class="sentence">5:09 I don't get bothered.</span>< <span class="sentence">I like the draftiness, I'm a little...</span><span class="sentence"> I'm one of the ones that opens the windows, and like—</span></p>
            </div>
            <div class="small-4 large-4 columns" id="annotations"><p></p>
            </div>
        </div>
    </section>

用于选择句子和添加注释的JS:

 <script>
        $('.sentence').click(function() {
            $(this).toggleClass('sentenceStyle');
            var y = $(this).offset().top;

            var para = document.createElement("p");
            $("#annotations").append(para);
            para.innerHTML="this is an annotation";
            para.css("position",'absolute');
            para.style.top = y;
        });
    </script>

这就是小提琴:http://jsfiddle.net/yujuns/HDe6v/3/

1 个答案:

答案 0 :(得分:1)

您希望在代码中更改某些内容。

首先你想要的是获得选择的偏移量。只有在选区周围放置一个html标签然后获得其偏移量时才会发生这种情况。然后,您可以通过将absoluteleft偏移设置为从html元素获得的偏移量来放置top定位消息框。

在下面的小提琴中,我展示了一个基本的实现,为您提供基本的想法。希望它有所帮助。

Fiddle

修改 试试这个小提琴更新。(回应作者的问题)。我已经添加了注释到我添加到js的代码行。我还为position: relative

添加了annotations到css

Updated Fiddle