繁体   English   中英

使用JS在html页面中选择一些文本

[英]Select some text in html page with JS

我想在div中自动选择文本(我的意思是“范围”),以便对JS中的脚本进行单元测试。

我的问题是我希望能够以不同的方式选择文本,这里是一些选择示例(由[代表开始,而]代表代表选择)

<div>[ here I select all the text in the div ]</div

<div>This is just a <b>piece [ of</b> selection]</div>

<div><ul><li>Also with [list</li><li>And why not select many items ?</li></ul><p>With a p ?] but not the complete p !</p>

我想这样做是因为用户可以这样做,所以我应该测试每种使用情况。 (如果我不这样做,则单元测试是完全没有用的...)

您对如何选择我想要的东西有想法吗? (如果可能的话...)

我在网上找到了这个。

该函数在对特定HTML元素进行调用时将自动选择其所有内部文本。 该功能适用​​于INPUT(文本),TEXTAREA,DIV,SPAN,TD和PRE等元素。 跨浏览器兼容。

var autoSelect = function(event) {
  var event = event || window.event, 
      elem = event.target || event.srcElement, 
      tag = (elem.tagName || "").toLowerCase(), 
      sel, range;

  if (tag === "textarea" || tag === "input") {
    try {
      elem.select();
    } catch(e) {
      // May be disabled or not selectable
    }
  } else if (window.getSelection) { // Not IE
    sel = window.getSelection();
    range = document.createRange();
    range.selectNodeContents(elem);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (document.selection) { // IE
    document.selection.empty();
    range = document.body.createTextRange();
    range.moveToElementText(elem);
    range.select();
  }
};

将此功能附加到元素:

document.getElementById("foobar").onclick = autoSelect;

您可以使用正则表达式进行操作:

var divStr = document.getElementById('yourDiv').innerHTML;
var matchs = /\[(.*?)\]/.exec(divStr);
console.log(matchs[1]);

我们获取内部html字符串,然后解析[]之间的所有内容,最后获取分组的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM