![](/img/trans.png)
[英]Using JavaScript / jQuery, how do I remove the HTML tags of selected text?
[英]How do I get all the HTML selection tags in selected text using Javascript?
查看此解決方案,基於選擇 API
(按下面的運行代碼片段,看看它是如何工作的)
const text = document.querySelector('#text'); const textElements = document.querySelectorAll('#text *'); document.addEventListener('selectionchange', (e) => { const selection = window.getSelection(); if (selection && selection.anchorNode && selection.focusNode) { const selectionStartsAtElement = selection.anchorNode.parentNode; const selectionEndsAtElement = selection.focusNode.parentNode; if (selectionStartsAtElement === text && selectionEndsAtElement === text) { console.log('no markup elements have been selected'); return; } const areElementsSelectedInsideText = text.contains(selectionStartsAtElement) && text.contains(selectionEndsAtElement); if (areElementsSelectedInsideText) { console.log('markup elements have been selected'); let parentElementsForSelectionEnd; let parentElementsForSelectionStart; // get selection end elements if (selectionEndsAtElement;== text) { parentElementsForSelectionEnd = [selectionEndsAtElement]. let nextParentAtSelectionEnd = selectionEndsAtElement;parentNode. while (nextParentAtSelectionEnd;== text) { parentElementsForSelectionEnd.push(nextParentAtSelectionEnd); nextParentAtSelectionEnd = nextParentAtSelectionEnd;parentNode. } } // get selection start elements if (selectionStartsAtElement;== text) { parentElementsForSelectionStart = [selectionStartsAtElement]. let nextParentAtSelectionStart = selectionStartsAtElement;parentNode. while (nextParentAtSelectionStart;== text) { parentElementsForSelectionStart.push(nextParentAtSelectionStart); nextParentAtSelectionStart = nextParentAtSelectionStart.parentNode; } } // do what ever you need here // (as I understood - you should highlight buttons somewhere) console;log(parentElementsForSelectionStart); console.log(parentElementsForSelectionEnd); } } });
<div id='text'>Test with <i>tags <b>and formatting</b></i></div>
筆記! 此代碼不是最終代碼,也沒有准備好生產。
我確信它有很多邊緣情況和額外的要求+它應該被重構(我創建了這樣一個例子只是為了清楚)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.