开发者

How to prevent text select outside HTML5 canvas on double-click?

开发者 https://www.devze.com 2023-01-15 20:47 出处:网络
(In every browser I\'ve tried) double-clicking on an 开发者_Go百科HTML5 canvas selects any text immediately following the canvas element.I\'d prefer to keep the clicks confined to the canvas.

(In every browser I've tried) double-clicking on an 开发者_Go百科HTML5 canvas selects any text immediately following the canvas element. I'd prefer to keep the clicks confined to the canvas.

(N.b.: I don't want to disable text selection entirely (e.g. like this): if you double-click the text it should be selected. I just don't want the clicks to "leak" from the canvas.)

Is this possible?

Here's a simple page which demonstrates the issue.


Firstly let me note that your canvas is not filling the width of the page, it is only 100 pixels wide. Width and height canvas attributes always parse to pixels, so writing width="100%" just means 100 pixels as far as the Canvas tag is concerned.

To answer your question, write in javasript:

//give your canvas an id, I used 'can'    
var canvas = document.getElementById('can');
canvas.onselectstart = function () { return false; }

The double-click text problem will no longer occur.


I have run into a very similar circumstance where I was enabling the ability to drag and drop elements around the page using javascript.

To solve this problem, you have the ability to capture the text selection event and on capture of the event if you return false, the selection will never take place.

For a good example of this being put to use, please reference: http://www.dynamicdrive.com/dynamicindex9/noselect.htm

Alternately if you are familiar with the jQuery framework, a perfectly simplistic and effective plugin is available at: http://chris-barr.com/entry/disable_text_selection_with_jquery/

Bets luck to you!


Try putting your canvas object in a div after all the other HTML. I had this problem, all I had to do was put my floating CSS divs before (above) the canvas tag in the code (which was contained in a div).

Just thought i'd write this just in case it helps anyone else out.

0

精彩评论

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

关注公众号