Home > Web Front-end > JS Tutorial > How to use js to achieve the effect of imitating the annotation function in world (code attached)

How to use js to achieve the effect of imitating the annotation function in world (code attached)

不言
Release: 2018-08-15 15:15:49
Original
4547 people have browsed it

The content of this article is about how to use js to achieve the effect of imitating the annotation function in the world (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

I am new to the front-end. I recently found out that there is an annotation function when using word, and I was thinking about how to use code to implement it.

1. The general requirements are as follows:

1. The page is divided into two parts: left, middle and right. The middle is the text content area, and the right and right sides are the annotation browsing area.
2. The annotation content displayed on the right must be on the same line as the required annotation vocabulary
3. Only two lines of content will be displayed initially, and all will be expanded when clicked
4. If the two annotated words are too close to each other, the annotation part must be sorted in order

2. Default solution

1. Add a p outside the annotation content, and use the min-height attribute of p to control the position of the annotation.
2. Use position: absolute absolute positioning to dynamically generate and change the position of the annotation.

3. Implementation process

In the process of implementing the above two methods, I found that the first solution would have bugs and the page would crash when the amount of data was huge. I gave up decisively and chose the second solution. Two ways to implement

1. Constant part:

1> args--------->A set of words with comments in the current article content
2> notes -------->Annotation text collection obtained from the library
3> rightWrap---->Right part annotation area object
4> leftWrap-----> Comment area object in the left part

2. Method part

1> setSite()----------------------- ------->Determine the position of the annotation when the initial interface is loaded
2> resetTop(elem, type)------------------->In Reset the position of all annotations when clicked
elem: the currently clicked object
type: (open/close) fully expand or partially display
3> bindClick(elem, type, selector, fn)-- -->Bind event function
elem: The element to which the event is bound
type: The bound event type, such as (click)
selector: The element dynamically added to elem
fn: Callback method after the binding event is executed

3. Overall code

1> index.html partial code

<p class="wrap">
    <aside class="left"></aside>
    <article class="center">
        <h3>人世</h3>
        <br />
        <p>使其停下来</p>
        <p>使光影、蜉蝣</p>
        <p><b class="special-0 nleft">众生</b>的所向是什么</p>
        <p>尤以静止方可得出</p>
        <p>我不做空明的阐述</p>
        <p>我是凡人,且一直落在凡尘里</p>
        <p>使云霞似锦吧</p>
        <p>若产出时间的黄金</p>
        <p>时间的<b class="special-1">黄金</b>只能在一颗心里</p>
        <p>播种,<b class="special-2">萌发</b>,成为照耀</p>
        <p>内敛的照耀比及月亮</p>
        <p>我们需做辉光的同谋人</p>
        <p>我们依旧不能成为闪电或是惊雷</p>
        <p>我们只是平凡的形形色色</p>
        <p>为所有悸动欢呼的应该是另一群人</p>
        <p>那些卑微的怯懦的都给我</p>
        <p>我隐在暗处说——</p>
        <p>“这很好!”,是的,你注视我说——</p>
        <p>“你很好!”</p>
        <p>还有可以使其堕落下去使其沦陷下去的吗</p>
        <p>光影、<b class="special-3">蜉蝣</b>、我和你</p>
        <p>和岸边无风也要摇荡的芦苇</p>
        <p>和似乎永不休止的蝉鸣</p>
        <p>和流水</p>
    </article>
    <aside class="right"></aside>
</p>
Copy after login

2> index.css partial code

.wrap {
    display: flex;
    position: relative;
    width: 100%;
}
article.center {
    flex: 1;
    text-align: justify;
    padding: 20px;
    border-right: 1px solid #ddd;
    border-left: 1px solid #ddd;
}
article.center p {
    line-height: 24px;
}
article.center p b {
    color: red;
}
aside.left, aside.right {
    width: 300px;
    padding: 20px 0;
}
.wrap aside mark {
    background-color: #fff;
    color: #afafaf;
    padding: 0 20px;
    position: absolute; 
    top: 0;
    height: 44px;
    overflow: hidden;
    line-height: 20px;
    font-size: 12px;
    text-align: justify;
    cursor: pointer;
    width: 260px;
}
Copy after login

3> Index.js part code

;
(function() {
    
//  构造函数
    function View(elem, notes, rightWrap, leftWrap) {
        this.rightWrap = rightWrap;
        this.leftWrap = leftWrap;
        this.args = typeof elem === 'object' ? elem : document.getElementById(elem);
        this.notes = notes === undefined ? [] : notes;
        
        this.init();
    }
    
//  原型
    View.prototype = {
        constructor: View,
        
        init: function() {
            var self = this;
            self.setSite();
            self.bindClick(document.body, 'click', 'mark', function (e) {
                var target = e.target;
                if(this.style.height) {
                    this.style.height = '';
                      self.resetTop(this, 'close');
                    return;
                } else {
                    this.style.height = this.scrollHeight +'px';
                      self.resetTop(this, 'open');
                }
            });
        },
        
//      设定初始高度
        setSite: function() {
            for(let i = 0; i < this.args.length; i++) {
//               默认新建的批注距离顶部的高度
                 var swdTop = 0;
                 var addMark = &#39;&#39;;
                 
//              计算当前批注的高度是否被覆盖,如果被覆盖,进行处理
                if(i > 0) {
                       if(this.args[i].offsetTop - this.args[i-1].offsetTop > $('.note-' + (i-1)).height()) {
                           swdTop = this.args[i].offsetTop - 2 + 'px';
                       } else {
                           swdTop = this.args[i-1].offsetTop + $('.note-' + (i-1)).height() - 2 + 'px';
                       }
                   } else {
                       swdTop = this.args[i].offsetTop - 2 + 'px';
                   }
                 
                 if(this.notes.length > 0) {
                     addMark = '<mark class="note-&#39; + i + &#39;" style="top:&#39; + swdTop + &#39;">'+ this.args[i].innerHTML     +':' + this.notes[i] + '</mark>';
                 } else {
                     addMark = '';
                 }
                 
//                 将得到的新标签动态添加到容器中
                   if(this.args[i].classList.length > 1 && this.args[i].classList[1] === 'nleft' && this.leftWrap !== undefined) {
                     this.leftWrap.append(addMark);
                 } else {
                     this.rightWrap.append(addMark);
                 }
             }
        },
        
//      重新设置元素高度
        resetTop: function(elem, type) {
            let index = parseInt(elem.className.substr(elem.className.indexOf('-')+1));
            for(; index < this.args.length-1; index++) {
                var swdNewTop = 0;
                var addTop = [];
                if(this.args[index+1].offsetTop - this.args[index].offsetTop > $('.' + elem.className).height()) {
                    console.log('我们不需要执行任何东西了')
                    return
                } else {
                    if(type === 'open') {
                        swdNewTop = this.args[index].offsetTop + $('.' + elem.className).height() + 8 + 'px';
                        addTop[index+1] = swdNewTop;
                    } else {
                        swdNewTop = this.args[index].offsetTop + $('.' +  elem.className).height() + 'px';
                    }
                    $('.note-' + (index+1)).attr('style', 'top:' + swdNewTop);
                    return
                }
            }
        },
        
//      绑定元素点击事件
        bindClick: function(elem, type, selector, fn) {
             if(fn === null) {
                 fn = selector;
                 selector = null;
             }
             elem.addEventListener(type, function(e) {
                 var target = e.target;
                 if(selector) {
                     target = e.target;
                     if(target.matches(selector)) {
                         fn.call(target, e);
                     }
                 } else {
                     fn(e);
                 }
             })
         }
    }
    
//  对外公开方法
    window.View = View;
})();
Copy after login

4. Extend the drag and drop method to an instance method of jquery through the extension method

(function($) {
  $.fn.extend({
    viewDocument: function(notes, rightWrap, leftWrap) {
      new View(this, notes, rightWrap, leftWrap);
      //  为了保证jQuery所有的方法能够实现链式访问,每个方法的最后必须返回this,即返回jquery的实例
      return  this;
    }
  })
})(jQuery);
Copy after login

5. Call the method on the main interface

//  此内容从数据库中获取,这里只是举个例子
let notes = [
         '山不在高,有仙则名;水不在深,有龙则灵;斯是陋室,惟吾德馨',
         '东边日出西边雨,道是无晴却有晴。一蓑烟雨任平生。桃李不言下自成蹊。会当凌绝顶,一览众山小。莫道不消魂,帘卷黄花瘦。',
         '得不到的永远在骚动,被宠爱的都有恃无恐,玫瑰的红,容易受伤的梦。',
         '青青园中葵,朝露待日晞。阳春布德泽,万物生光辉。常恐秋节至,焜黄华叶衰。百川东到海,何时复西归?少壮不努力,老大徒伤悲!'
     ];
//  获取注释所在的容器
let rightWrap = $('aside.right');
let leftWrap = $('aside.left');
$('.center b').viewDocument(notes, rightWrap, leftWrap);
Copy after login

Related recommendations:

Use js to imitate the word format brush function to implement code [Recommended]_javascript skills

PHP to imitate Baidu Library , Docin online document effect (word, excel, ppt to flash), _PHP tutorial

js Word table dynamically adds code_javascript skills

The above is the detailed content of How to use js to achieve the effect of imitating the annotation function in world (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template