javascript - 仅在特定 div 中替换选定的 HTML
问题描述
我想选择用户在 contenteditable div 中选择的任何内容的 HTML。我找到了一些代码来检索选择的 HTML,但它不仅限于 div。
我想要做的是复制选定的 HTML,将标签包裹起来,然后用它替换选择。因此,例如,“测试”将变为“测试”。
<div contenteditable="true" class="body" id="bodydiv"></div>
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
}
解决方案
嗨,在选定的 div 中获取内容(文本)我已经创建了一个小代码,你可以检查一下它是否适合你:
$(document).ready(function(){
$(document).bind('mouseup', function(){
var content = getSelected();
content = "<b>"+content+"</b>";
$('#selected').html(content);
});
});
function getSelected(){
var t;
if(window.getSelection){
t = window.getSelection();
var start = t.focusOffset;
var end = t.baseOffset;
t = t.anchorNode.data;
t = t.slice(start, end);
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
和
<div id="selected"></div>
希望这可以帮助。
推荐阅读
- linux - 启动 mongodb 服务器时出错
- c++ - 同一文件的不同哈希值(使用 ifstream 完成读取)
- python - 使用标准 1 行编写列表 - Python
- mongodb - 如何使用 mongodump 备份 mongo 集合列表以存档
- php - paypal用户名密码signautre和帐户clientID和secret有什么区别
- python - 内核已死并在运行单元以训练回归模型时自动重新启动
- angular - Angular HttpClient.get() 不返回完整的响应标头
- rspec - Rspec 测试语言环境是否具有相同的键
- reactjs - 如何将自定义样式添加到 npm 模块 powerBi-report-component
- c# - ASP.NET Core - 在单例中使用配置