1 回答
TA贡献1818条经验 获得超8个赞
嗯,不是你想要的,但更接近你的要求。它是这样的:
将您的脚本更新为如下:
<script>
const container = document.querySelector('.storypara');
const popupContainer = document.querySelector('.popupContainer');
// this method is added
// It gives the text of HTML of selected text :)
function getHTMLOfSelection () {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
container.addEventListener('mouseup', (e) => {
const selectedText = getHTMLOfSelection(); // First get the raw HTML text
if (selectedText) {
//selectedText.split("<").join("<"); // Now replacing the < so that browser don't render it
//selectedText.split(">").join(">"); // Also replacing the > so that browser don't render it
//console.log(selectedText);
showPopup(selectedText); // using the 'xmp' tags around the text, to show the html as it is
}
});
popupContainer.addEventListener('click', (event) => {
if (event.target.matches('.popupContainer')) {
popupContainer.classList.remove('show');
}
});
function showPopup(selectedText) {
// set the selected text as html inside popup element
document.querySelector('.popup').innerHTML = selectedText;
popupContainer.classList.add('show');
}
</script>
我添加了一个函数,它为您提供所选文本的 HTML。这就是向用户显示 HTML 所能做的所有事情。希望能帮助到你。
如果它对您不起作用,请告诉我:) 很乐意为您提供帮助
添加回答
举报