Created
July 18, 2024 05:29
-
-
Save azzgo/71de889526ca7a076503b0bc5da49b5f to your computer and use it in GitHub Desktop.
quil-marks.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./style.css"; | |
import "quill/dist/quill.snow.css"; | |
import Quill from "quill"; | |
const editorEl = document.getElementById("editor"); | |
const markerListEl = document.getElementById('marker-list'); | |
const markers = {} | |
const quill = window.editor = new Quill(editorEl, { theme: "snow" }); | |
function addMarker() { | |
const range = quill.getSelection(); | |
if (range && range.length > 0) { | |
const markerId = 'marker-' + Date.now(); | |
// 标记选中的文本 | |
quill.formatText(range.index, range.length, {'data-marker-id': markerId, 'color': 'rgb(0, 0, 255)'}); | |
markers[markerId] = {index: range.index, length: range.length}; | |
const markerItemEl = document.createElement('li'); | |
markerItemEl.textContent = markerId; | |
markerItemEl.addEventListener('click', () => gotoMarker(markerId)) | |
markerListEl.appendChild(markerItemEl); | |
} | |
} | |
quill.on('text-change', function(delta) { | |
delta.ops.forEach(function(op) { | |
if (op.insert) { | |
var insertIndex = op.insert.length; | |
for (let markerId in markers) { | |
// 如果插入文本在标记前面或中间,则更新标记位置 | |
if (markers[markerId].index >= insertIndex) { | |
markers[markerId].index += insertIndex; | |
} | |
} | |
} else if (op.delete) { | |
var deleteIndex = op.delete.length; | |
for (let markerId in markers) { | |
if (markers[markerId].index >= deleteIndex) { | |
markers[markerId].index -= deleteIndex; | |
} | |
} | |
} | |
}); | |
}); | |
// 返回到标记位置 | |
function gotoMarker(markerId) { | |
const marker = markers[markerId]; | |
if (marker) { | |
quill.setSelection(marker.index, marker.length); | |
} | |
} | |
// 示例按钮绑定 | |
document.getElementById('addMarkerBtn').addEventListener('click', addMarker); | |
document.getElementById('gotoMarkerBtn').addEventListener('click', function() { | |
gotoMarker(document.getElementById('marker-id').value); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment