开发者

JS/CSS/XHTML: Don't copy specific text during copy events

开发者 https://www.devze.com 2023-02-26 00:54 出处:网络
I\'m looking for a way to disable the copying of a specific area of text when you use Ctrl + C, etc. Whether I have to write the text a different way or not.

I'm looking for a way to disable the copying of a specific area of text when you use Ctrl + C, etc. Whether I have to write the text a different way or not.

http://gyazo.com/721a0a5b5af173beb1ad3305633beafb.png

Above is what this is for. It's a syntax highlighter I have been working on (3 languages supported so far). When the user selects ANY text in any way, I don't want the line numbers to be copied.

I 开发者_开发技巧can't think of a way to display line numbers, without them actually being there.


As long as the line numbers and the source code are mixed together, this is going to be tough to prevent programmatically, if not impossible.

The ideal way would be having the source code in an actual container of its own.

Open a document inspector and look at how Github do it, for example: https://github.com/jbrisbin/riak-exchange/blob/master/Makefile

they have a separate <pre> element containing the line numbers, and a <table> cell containing the code. (I assume selecting is a reason why they use tables here, but I do not know for sure.)


Give this a try...

Demo: http://jsfiddle.net/wdm954/UD8Dq/7

I layered the div so the code div is on top and the numbers are behind. When you copy and paste you should just get the code.

.lines {
    position: absolute;
    width: 80%;
    color: #666;
}
.lines pre:nth-child(odd) {
    background-color: #EEE;
}
.code {
    position: absolute;
    z-index: 2;
    padding-left: 5%;
    width: 80%;
}


<div class="box">
    <div class="lines">
        <pre>1</pre>
        <pre>2</pre>
        <pre>3</pre>
        <pre>4</pre>
    </div>
    <div class="code">
<pre>
    code
    code
    code
    code
</pre>
    </div>
</div>


Setting user-select, -moz-user-select, and -webkit-user-select to none might work. For IE, you will need to handle onselectstart and return false.

This will prevent people from selecting the text, but I don't know what happens when it's beside other text that you attempt to copy.


I know that this question is three years old, but with HTML5 you can store line numbers in a data attributes and use CSS2 to display the text. This should prevent line numbers from being copied.

HTML

<span data-line-number='1' class='line'></span>

CSS

.line:before {
    content: attr(data-line-number);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消