window.getSelection().getRangeAt()无法正常工作 [英] window.getSelection().getRangeAt() not working properly

查看:384
本文介绍了window.getSelection().getRangeAt()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在html元素中获取文本选择,然后在其周围插入span标签.到目前为止,我在使用正确的索引时遇到了问题.如果我突出显示<p>块内的文本,则在<br>标记后索引将变为0.我希望能够对文本进行slice(),然后在突出显示文本以及抓取所选文本并将其通过Ajax发送到服务器之后,使用span标签将其重新组合.

I am trying to get the text selection within a an html element and then insert span tags around it. So far, I am having problems with the correct indices. If I highlight text inside a <p> block, the index goes to 0 after a <br> tag. I want to be able to slice() the text out and then recombine it with span tags after highlighting the text as well as grabbing the selected text and sending it to server via Ajax.

以下是一些示例HTML和代码:

Here is some sample HTML and code:

<html><body><p>This is some sample text.<br>Select this text.</p></body></html>

jQuery:

$('*').mouseup(function() {
    mouseDown = false;

    var startIndex = window.getSelection().getRangeAt(0).startOffset;
    var endIndex = window.getSelection().getRangeAt(0).endOffset;
    alert($(body *).text().slice(startIndex, endIndex));
});

推荐答案

好吧,我在jsfiddle上查看了您的代码,问题似乎是javascript不知道"highlightedElement"是什么,所以我嘲笑了一个小演示在jsfiddle上为您服务....

Well i had a look at your code on jsfiddle and the problem seemed to be that javascript didn't know what "highlightedElement" was so i mocked a little demo up for you on jsfiddle....

它有点脆弱,但是它应该做您需要做的事情: http://jsfiddle.net/WRrH9/5/

It's a bit fragile but it should do what you need it to do: http://jsfiddle.net/WRrH9/5/

如果由于某种原因它不起作用,请修改您的代码:

In case it doesn't work for some reason heres your code modified:

HTML:

<html>
    <head>
    </head>
    <body>
        <p>This is some sample text.Select this text.
        </p>
    </body>
</html>​

JavaScript:

JavaScript:

$('body *').mouseup(function() {
    mouseDown=false;
    var startIndex = window.getSelection().getRangeAt(0).startOffset;
    var endIndex = window.getSelection().getRangeAt(0).endOffset;
    var slicedText = $(this).text().slice(startIndex, endIndex);
    $(this).html($(this).text().replace(slicedText,'<span>' + slicedText + '</span>'));
});​

希望这会有所帮助!

这篇关于window.getSelection().getRangeAt()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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