gpt4 book ai didi

javascript - 单击按钮更改所选文本的 html

转载 作者:行者123 更新时间:2023-12-01 03:42:10 24 4
gpt4 key购买 nike

我试图在单击按钮后在选定的文本上添加一些文本。

我有一个可编辑内容的区域,如下图所示。

我想选择文本,选择后,当我单击 B 图标时,我想在所选文本周围添加一些 html 标签,例如

<b>make this text bold</b>

或者等等

enter image description here

我在 stackoverflow 上找到了这些代码;

这个以文本形式返回我的选择。

function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}

如果我将它们一起使用,这个会根据需要更改文本的 html。

function replaceSelectionWithHtml(html) {
var range;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = html;
var frag = document.createDocumentFragment(), child;
while ( (child = div.firstChild) ) {
frag.appendChild(child);
}
range.insertNode(frag);
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.pasteHTML(html);
}
}
replaceSelectionWithHtml("<b>" + getSelectionText() + "</b>");

但是当我单击图标时,它会失去焦点并选择按钮作为选择,并为 B 图标运行replaceSelectionWithHtml()。

我如何激活这些任务?

这是代码笔链接:https://codepen.io/anon/pen/ybzzXZ它的功能并不完整,但我会给你一个更好的主意。

最佳答案

    function getSelectionText() {
var text = "";
if (window.getSelection) {
alert(window.getSelection())
text = window.getSelection();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}



var selection;
var isDown = false;

$(".nText").mousedown(function(){
isDown = true;
});

$(document).mouseup(function(){
if(isDown){
selection = getSelectionText();
alert(selection);

//do something
isDown = false;
}
});
document.onmouseup = document.onkeyup = document.onselectionchange = function() {



};

关于javascript - 单击按钮更改所选文本的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com