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)
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> <aside></aside> <article> <h3 id="人世">人世</h3> <br> <p>使其停下来</p> <p>使光影、蜉蝣</p> <p><b>众生</b>的所向是什么</p> <p>尤以静止方可得出</p> <p>我不做空明的阐述</p> <p>我是凡人,且一直落在凡尘里</p> <p>使云霞似锦吧</p> <p>若产出时间的黄金</p> <p>时间的<b>黄金</b>只能在一颗心里</p> <p>播种,<b>萌发</b>,成为照耀</p> <p>内敛的照耀比及月亮</p> <p>我们需做辉光的同谋人</p> <p>我们依旧不能成为闪电或是惊雷</p> <p>我们只是平凡的形形色色</p> <p>为所有悸动欢呼的应该是另一群人</p> <p>那些卑微的怯懦的都给我</p> <p>我隐在暗处说——</p> <p>“这很好!”,是的,你注视我说——</p> <p>“你很好!”</p> <p>还有可以使其堕落下去使其沦陷下去的吗</p> <p>光影、<b>蜉蝣</b>、我和你</p> <p>和岸边无风也要摇荡的芦苇</p> <p>和似乎永不休止的蝉鸣</p> <p>和流水</p> </article> <aside></aside> </p>
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;
}
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 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>'+ 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 $('.' + 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;
})();
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);
5. Call the method on the main interface
// 此内容从数据库中获取,这里只是举个例子
let notes = [
'山不在高,有仙则名;水不在深,有龙则灵;斯是陋室,惟吾德馨',
'东边日出西边雨,道是无晴却有晴。一蓑烟雨任平生。桃李不言下自成蹊。会当凌绝顶,一览众山小。莫道不消魂,帘卷黄花瘦。',
'得不到的永远在骚动,被宠爱的都有恃无恐,玫瑰的红,容易受伤的梦。',
'青青园中葵,朝露待日晞。阳春布德泽,万物生光辉。常恐秋节至,焜黄华叶衰。百川东到海,何时复西归?少壮不努力,老大徒伤悲!'
];
// 获取注释所在的容器
let rightWrap = $('aside.right');
let leftWrap = $('aside.left');
$('.center b').viewDocument(notes, rightWrap, leftWrap);
Related recommendations:
Use js to imitate the word format brush function to implement code [Recommended]_javascript skills
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!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools






