使用Java脚本获取选定内容的开始和结束 [英] Get start and end of a selection using javascript

查看:23
本文介绍了使用Java脚本获取选定内容的开始和结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的html字符串:

<div id="div">Hi how are<span>you?</span> Fine</div>

文本将显示"Hi how are you? Fine"

我想用鼠标选择字符串的一部分,并获得开头和结尾 从全文字符串查看所选内容。

例如,如果我选择"You",我希望获取Start=11和End=14;

如果我选择"Are You?",我希望获得Start=7和End=15。

我写这个是为了获得选择:

function getSel() {
            console.log(navigator.appCodeName);
            if (window.getSelection) {
                return window.getSelection();
            } else if (document.getSelection) {
                return document.getSelection();
            } else if (document.selection) {
                return document.selection.createRange().text;
            }
        }

和此代码获取开始和结束,但不起作用:

$("#div").on('mouseup', function(e){
            var text=getSel();
            if(text.anchorNode === text.focusNode){
                var n = {  
                    node: text.anchorNode.parentNode.id,
                    start: text.anchorOffset,
                    end: text.focusOffset
                }
                //selection from right to left
                if(n.start>=n.end) {  
                    var tmp;
                    tmp=n.start;
                    n.start=n.end;
                    n.end=tmp;
                }
            }
            else    console.log("error in selection");          
});

推荐答案

您的选择器错误。$('#div')实际选择具有id='div'的所有元素。

我举了一个如何做到这一点的例子。如果我没有弄错你想要达到的目的。

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

$(function(){
  $("#div").on('mouseup', function(e){
    var thisText = $(this).text();
    var selectedText = getSelectionText();
    var start = thisText.indexOf(selectedText);
    var end = start + selectedText.length;
    if (start >= 0 && end >= 0){
        console.log("start: " + start);
        console.log("end: " + end);
    }
  });
});

Fiddle

这篇关于使用Java脚本获取选定内容的开始和结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆