交互式选择在浏览器中突出显示文本

时间:2015-03-02 22:21:31

标签: javascript jquery selection highlight interactive

我需要的是通过Javascript在浏览器中突出显示文本。

更具体地说,我只想说我在div元素中有一堆文字,如下所示:

<div>The quick brown fox jumps over the lazy dog ... </div>

现在我想要做的是选择这个文本的某个范围并突出显示它(即&#34;棕色狐狸&#34;)。我已经通过使用rangy.js来实现这一点。

现在我真的想让这个选择/突出显示更具交互性,以便用户可以抓住选择的开头或结尾(使用某种句柄)并通过拖动开头或结尾来交互式地调整选择的大小。当前选择到新的起点或终点。

我试图谷歌,但无法找到任何东西。更糟糕的是,我完全不知道应该如何开始实施这样的事情。

也许有人可以指出我正确的方向,甚至可以更好地了解如何开始实施这样的事情。

非常感谢您的帮助......

2 个答案:

答案 0 :(得分:4)

这个问题相当复杂,并且因浏览器缺乏一致性而受到阻碍。但是,我已经对这个问题进行了一定程度的成功。

Test out my solution with this jsfiddle

Edit: more robust solution

我不保证这适用于所有情况,我的测试目前仅限于文本。还有一些问题需要解决,我将在不久的将来解决。但是,我认为它已准备好在这里发布。

方法

问题可分为几个步骤。首先,我们需要在用户的选择周围插入标记。尽管有一些必须解决的设计决策,但这并不困难。经过一些实验,我决定在标记位置直接插入文档;然后,更容易在这些标记之间选择内容。下面是插入标记方法。

function insertMarker (isBefore) {
    var range;

    if (window.getSelection) {
        // IE9+ and non-IE
        var sel = window.getSelection();

        if (sel.getRangeAt) {
            range = window.getSelection().getRangeAt(0);
            range.collapse(isBefore);
        }
    } else if (document.selection && document.selection.createRange) {
        // IE < 9
        range = document.selection.createRange();
        range.collapse(isBefore);
    }

    // Create the marker element and insert it into the DOM.
    if (range) {
        range.insertNode(createMarker(isBefore));
    }
}

其次,用户必须能够在文档周围拖动这些标记,以便它们在字符/可选内容之间锁定。这可以使用document.caretPositionFromPoint(x, y)(标准)或document.caretRangeFromPoint(x, y)(WebKit)来实现。

第三,移动标记时,必须更新选择以反映此更改。这可以使用range.setStartAfterrange.setEndBefore来实现,尽管有不同的Range实现,但大多数浏览器都支持这些。{/ p>

function selectSelection () {
    if (window.getSelection) {
        // IE9+ and non-IE
        var sel = window.getSelection();
        var range = document.createRange();
        range.setStartAfter($(".marker").get(0));
        range.setEndBefore($(".marker").get(1));
        sel.removeAllRanges();
        sel.addRange(range);
    }
    else if (document.selection && document.selection.createRange) {
        // IE < 9
        var range = document.selection.createRange();
        range.setStartAfter($(".marker").get(0));
        range.setEndBefore($(".marker").get(1));
    }
}

答案 1 :(得分:1)

尝试

HTML

<div id="selectable"></div>
<br />
<hr />
<button id="clear">clear selections</button>
<hr />
<br />
<div id="selections">
  <div class="selected"></div>
</div>

CSS

#selectable .ui-selecting {
  background: #FECA40;
}
#selectable .ui-selected {
  background: #F39814;
  color: white;
}
#selections {
  width: 100%;
  height: 400px;
}
#clear {
  position: relative;
  left: calc(37%);
}
.selected {
  width: 150px;
  height: 150px;
  overflow: hidden;
}
.selected,
.text {
  display: block;
  background-color: rgb(225, 225, 225);
}
.ui-widget-content {
  border: 1px dotted rgba(170, 170, 170, .25);
}
.ui-widget-conent span {
  display: inline-block;
  padding: 4px;
  margin: 4px;
}

JS

  var selectable = $("#selectable") // selectable words
  , selections = $("#selections") // selected words container parent
  , selected = $(".selected") // selected words container
  , clear = $("#clear") // clear all
  , sel = ".ui-selected" // selected word
  , content = ".ui-widget-content" // selectable words element `class`
  , text = ".text" // selected words draggable, resizable container `class`
  , handles = {} // resize handles
  , str = "The quick brown fox jumps over the lazy dog ..." // text, `string`
    // split `str`, return array of words
  , words = str.split(" ").map(function(word, i) {
      $("<span />", {
        "class": content.slice(1),
        "text": word,
        "css": {
          "margin": "2px"
        }
      }).appendTo(selectable)
    });
  // append `handles` to `text` container
  $.each(["nw", "ne", "sw", "se"], function(_, handle) {
    var elem = $("<div />", {
        "class": "ui-resizable-handle ui-resizable-" + handle,
        "css": {
          "width": "calc(12px + 5%)",
          "height": "calc(12px + 5%)",
          "border-radius": "50%",
          "background": "#000"
        }
      })
      .appendTo(selected)
      .parent().find(":last")
      .css({
        "right": "-5px",
        "bottom": "-5px"
      });
    handles[handle] = elem[0];
  });
  // `selected` settings
  // set `selected` `display` to `none`
  selected
  .hide(0)
  .resizable({
      handles: handles
  })
  .draggable({
      containment: "parent"
  });
  // collect selected words at `selectable.data("selections", [])` array,
  // append words to `text`,
  // append `text` to `selected`,
  // set `selected` `display` to `block`
  selectable.data("selections", [])
    .selectable({
      selected: function(event, ui) {
        $(this).data("selections").push($(ui.selected).text())
      },
      stop: function() {
        selected
          .find(".text")
          .remove()
          .addBack()
          .prepend(
            $("<div />", {
              "class": "text",
              "text": $(this).data("selections").join(" "),
              "css": {
                "position": "relative",
                "display": "block",
                "padding": "calc(15%)",
                "height": "calc(50%)",
                "white-space": "pre-line",
                "overflow": "hidden"
              }
            })
          ).show(0)
      }
    });
  // remove selected words from `selectable.data("selections", [])` array,
  // remove `sel` `class` from `selectable` words,
  // remove `text`,
  // set `selected` display to `none`
  clear.on("click", function(e) {
    selectable.data("selections", [])
      .find(sel).removeClass(sel.slice(1));
    selections.find(text).remove()
      .addBack().find(selected).hide(0)
  });

jsfiddle http://jsfiddle.net/guest271314/dpt9bn0n/

请参阅jQuery UI SelectableDraggableResizable

&#13;
&#13;
$(function() {

  var selectable = $("#selectable") // selectable words
  , selections = $("#selections") // selected words container parent
  , selected = $(".selected") // selected words container
  , clear = $("#clear") // clear all
  , sel = ".ui-selected" // selected word
  , content = ".ui-widget-content" // selectable words element `class`
  , text = ".text" // selected words draggable, resizable container `class`
  , handles = {} // resize handles
  , str = "The quick brown fox jumps over the lazy dog ..." // text, `string`
    // split `str`, return array of words
  , words = str.split(" ").map(function(word, i) {
      $("<span />", {
        "class": content.slice(1),
        "text": word,
        "css": {
          "margin": "2px"
        }
      }).appendTo(selectable)
    });
  // append `handles` to `text` container
  $.each(["nw", "ne", "sw", "se"], function(_, handle) {
    var elem = $("<div />", {
        "class": "ui-resizable-handle ui-resizable-" + handle,
        "css": {
          "width": "calc(12px + 5%)",
          "height": "calc(12px + 5%)",
          "border-radius": "50%",
          "background": "#000"
        }
      })
      .appendTo(selected)
      .parent().find(":last") // `se` 
      .css({
        "right": "-5px",
        "bottom": "-5px"
      });
    handles[handle] = elem[0];
  });
  // `selected` settings
  // set `selected` `display` to `none`
  selected
    .hide(0)
    .resizable({
      handles: handles
    })
    .draggable({
      containment: "parent"
    });
  // collect selected words at `selectable.data("selections", [])` array,
  // append words to `text`,
  // append `text` to `selected`,
  // set `selected` `display` to `block`
  selectable.data("selections", [])
    .selectable({
      selected: function(event, ui) {
        $(this).data("selections").push($(ui.selected).text())
      },
      stop: function() {
        selected
          .find(".text")
          .remove()
          .addBack()
          .prepend(
            $("<div />", {
              "class": "text",
              "text": $(this).data("selections").join(" "),
              "css": {
                "position": "relative",
                "display": "block",
                "padding": "calc(15%)",
                "height": "calc(50%)",
                "white-space": "pre-line",
                "overflow": "hidden"
              }
            })
          ).show(0)
      }
    });
  // remove selected words from `selectable.data("selections", [])` array,
  // remove `sel` `class` from `selectable` words,
  // remove `text`,
  // set `selected` display to `none`
  clear.on("click", function(e) {
    selectable.data("selections", [])
      .find(sel).removeClass(sel.slice(1));
    selections.find(text).remove()
      .addBack().find(selected).hide(0)
  });

  // do stuff
  var phrase = [0, 1, 2, 8, 4, 5, 6, 7, 3, 9];
  setTimeout(function() {
    $.when(
        selectable.queue("phrase", $.map(phrase, function(word, i) {
          return function(next) {
            return $.when(!$(this).find(content).eq(word)
              .addClass("ui-selecting").parent()
              .data("ui-selectable")._mouseStop(false) && $(this)
            ).then(function(el) {
              return el.delay(2000);
            }).then(next)
          }
        })
        )
        .dequeue("phrase").promise("phrase")
      , clear
    )
    .then(function(el, button) {
        button.trigger("click")
    });
  }, 2713);

});
&#13;
#selectable .ui-selecting {
  background: #FECA40;
}
#selectable .ui-selected {
  background: #F39814;
  color: white;
}
#selections {
  width: 100%;
  height: 400px;
}
#clear {
  position: relative;
  left: calc(37%);
}
.selected {
  width: 150px;
  height: 150px;
  overflow: hidden;
}
.selected,
.text {
  display: block;
  background-color: rgb(225, 225, 225);
}
.ui-widget-content {
  border: 1px dotted rgba(170, 170, 170, .25);
}
.ui-widget-conent span {
  display: inline-block;
  padding: 4px;
  margin: 4px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" 
      rel="stylesheet" />
<div id="selectable"></div>
<br />
<hr />
<button id="clear">clear selections</button>
<hr />
<br />
<div id="selections">
  <div class="selected"></div>
</div>
&#13;
&#13;
&#13;