Is it possible to restrict the range of select all/Ctrl+A?

 ̄綄美尐妖づ 提交于 2020-01-02 05:21:05

问题


I am working on a website where I would like to be able to display a box containing syntax-highlighted source code for the user to copy. When I click on the box, giving it focus (Chrome shows its focus outline), and type Ctrl+A, the text of the entire page is selected, whereas I would like only the syntax-highlighted source code within the box to be selected.

Is it possible to restrict the range of select all/Ctrl+A to only the text within the box, preferably without using an <iframe>?

My first thought was to try contenteditable. When I click in the box and the editor caret appears, typing Ctrl+A selects only the text within the box, as desired, but it also allows the user to change the code, and I think that the editor-interface aspect of making the box contenteditable will be confusing to users. If I wrap the source code text within a <div> having contenteditable="false" within the <div> having contenteditable="true", then the source code text is read-only, but typing Ctrl+A selects the text of the entire page again.

Here is a test page: http://jsfiddle.net/5crgL/


回答1:


You can use the document.createRange(); method to select the text from a particular element. and to handle the ctrl+a you can use the jQuery keydown method and can call the JS code to select the DIV text.

var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);

please see jsfiddle here jsfiddle.



来源:https://stackoverflow.com/questions/24553251/is-it-possible-to-restrict-the-range-of-select-all-ctrla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!