javascript - 获取 HTML 选择

标签 javascript html

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;
        }
    }
    return html;
}

我正在使用此处提供的上述代码:How to get selected html text with javascript? .

但是,实际的 html 和函数返回的 html 存在如此不一致的地方。例如,给定以下 html:

<div>
<p><b>The quick brown fox jumps over the lazy <a href="www.google.com">dog</a></b></p>
<img src="http://www.fakingnews.firstpost.com/wp-content/uploads/2015/12/kim-jaya.jpg" alt="Smiley face" height="42" width="42">
<hr>
<p>The quick brown fox jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
    <ul>1</ul>
    <ul>2</ul>
    <ul>3</ul>
    <ul>4</ul>
    <ul>5</ul>
</li>
</div>
<br />
<input id="showSelected" type="button" value="showSelected" />

如果我要选择

x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
    <ul>1</ul>
    <ul>2</ul>
    <ul>3</ul>

函数实际返回

<div><p>x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
    <ul>1</ul>
    <ul>2</ul>
    <ul>3</ul>
    <ul>4</ul>
    <ul>5</ul>
</li>
</div>

我注意到,当我还选择一个列表时,前面会出现额外的标签,但我确信还有其他不一致的情况。我能做些什么来获得准确的 HTML 副本吗?

最佳答案

由于您选择的不是有效的 HTML,例如缺少开始和结束标记,因此您在问题中列出的代码将无法按预期工作, 在您的情况下,您需要使用文本选择功能,例如:https://stackoverflow.com/a/169873/200713

function getSelectedText() {
  var txt = '';

  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 

  return txt;
}

关于javascript - 获取 HTML 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42192921/

相关文章:

javascript - 如何在 Klaviyo 中将数字转换为逗号分隔值

html - 在 vps 上传输我的 django 元素时出现问题

php - 选择国家 HTML PHP

javascript - Angular 1.6.3 不允许 1.5.8 中允许的 JSONP 请求

javascript - 函数无法正确读取值

javascript匹配()错误

html - 单击外部关闭模式(仅限 CSS + HTML)

html - 以单一表格提交文本和图像/视频

html - 如何在 HTML 文档中混合使用希伯来文和拉丁文文本?

javascript - 根据重复的字典属性将一维列表减少为锯齿状二维列表