在网页中设置最大文本选择范围

时间:2013-12-02 23:43:22

标签: select text copy range max

我想用javascript在我的网页上设置文本选择限制。 我的意思是说 - 如果有人试图用鼠标光标选择文本(或按ctrl + a),最大选择范围必须是100个字符,即他将从我的页面复制最多100个字符。有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以检测选择更改事件(IE和WebKit支持document上的selectionchange事件,您可以在其他浏览器中使用各种其他键和鼠标相关事件)并使用{{但是在做这个之前我会仔细考虑:它打破了用户期望的标准选择行为,我无法想象它值得的情况。

答案 1 :(得分:0)

这是我的最终解决方案:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>test</title>
  </head>
  <body>
<script language="javascript" type="text/javascript">
document.onselectionchange = zzz;

function zzz()
{
var selectedRange = returnSelection();

    if(selectedRange.length>50)
    {
    //alert('opaaaa');
    deselectSelection();
    }

}

function returnSelection()
{
    if (window.getSelection)
        {
        if (window.getSelection().toString().length > 0)
        {
        return window.getSelection().toString();
        }
    }
    else if (document.getSelection)
    {
        if (document.getSelection().toString().length > 0)
        {   
        return document.getSelection().toString();
        }
    }
        else if (document.selection)
    {
        if (document.selection.createRange().text.toString().length > 0)
        {       
        return document.selection.createRange().text.toString();
        }
    }
    return false;
}
function deselectSelection()
{       
    if (window.getSelection) 
    {
        if (window.getSelection().empty) // Chrome
        {  
        window.getSelection().empty();
        } 
        else if (window.getSelection().removeAllRanges) // Firefox
        { 
        window.getSelection().removeAllRanges();
        }
    } 
        else if (document.selection) // IE?
    {  
    document.selection.empty();
    }
}
</script>

  <p>
  A web page could be considered as a document tree that can contain any number of     branches. There are rules as to what items each branch can contain (and these are detailed     in each element’s reference in the “Contains” and “Contained by” sections). To understand     the concept of a document tree, it’s useful to consider a simple web page with typical     content features alongside its tree view, as shown in
  </p>
  </body>
</html>