- Быстро и кратко, полно и точно — Ruby on Rails, PHP, MySQL, CodeIgniter, JQuery
- вторник, 12 июля 2011 г.
- jQuery, CSS. Как отключить выделение мышкой текста для отдельного блока
- Мышь: отмена выделения, невыделяемые элементы
- Способ 1: отмена mousedown/selectstart
- Способ 2: снятие выделения постфактум
- Способ 3: свойство user-select
- IE9-: атрибут unselectable=«on»
- Итого
- How do websites block selecting text and how do I unblock that?
- MozUserSelect style property | webkitUserSelect style property
- Syntax:
- Possible values:
- Example HTML code 1:
- Example HTML code 2:
- Example HTML code 3:
- Example HTML code 4:
- Supported by objects:
Быстро и кратко, полно и точно — Ruby on Rails, PHP, MySQL, CodeIgniter, JQuery
Основная задача блога — стать стартовой платформой для начинающих разработчиков, здесь не только буду писать свои статьи, но также буду выкладывать полезные ссылки которые помогут разобраться в разных вопросах. Будут затронуты темы: Ruby on Rails, PHP, MySQl, CodeIgniter, JQuery.
вторник, 12 июля 2011 г.
jQuery, CSS. Как отключить выделение мышкой текста для отдельного блока
Иногда нужно запретить выделение текста в некоторых блоках — например при динамическом изменении размера, текст блока будет выделяться, что не есть красиво.
Решений тут два: используем jQuery либо CSS.
$(".classname").attr('unselectable','on').css('MozUserSelect','none');
Учитывая пожелания высказанные в комментариях, привожу пример яваскриптового отключения выделения (организованного в плагин), с явным отключением самого ивента ‘onselectstart’, а также содержащий весь уже выше перечисленный функционал:
jQuery.fn.extend(< disableSelection : function() < this.each(function() < this.onselectstart = function() < return false; >; this.unselectable = "on"; jQuery(this).css(< '-moz-user-select': 'none', '-khtml-user-select': 'none', '-webkit-user-select': 'none', '-o-user-select': 'none', 'user-select': 'none' >); >); >, enableSelection : function() < this.each(function() < this.onselectstart = function() <>; this.unselectable = "off"; jQuery(this).css(< '-moz-user-select': 'auto', '-khtml-user-select': 'auto', '-webkit-user-select': 'auto', '-o-user-select': 'auto', 'user-select': 'auto' >); >); > >); // Example: var selector = "td, span, div"; $(selector).disableSelection(); // disable . $(selector).enableSelection(); // enable
Мышь: отмена выделения, невыделяемые элементы
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/selection-range.
У кликов мыши есть неприятная особенность.
Двойной клик или нажатие с движением курсора как правило инициируют выделение текста.
Если мы хотим обрабатывать эти события сами, то такое выделение – некрасиво и неудобно. В этой главе мы рассмотрим основные способы, как делать элемент невыделяемым.
Для полноты картины, среди них будут и такие, которые применимы не только к событиям мыши.
Способ 1: отмена mousedown/selectstart
Проблема: браузер выделяет текст при движении мышью с зажатой левой кнопкой , а также при двойном клике на элемент. Даже там, где это не нужно.
Если сделать двойной клик на таком элементе, то обработчик сработает. Но побочным эффектом является выделение текста браузером.
Чтобы избежать выделения, мы должны предотвратить действие браузера по умолчанию для события selectstart в IE и mousedown в других браузерах.
Полный код элемента, который обрабатывает двойной клик без выделения:
Двойной клик сюда выведет "Тест", без выделения
При установке на родителя – все его потомки станут невыделяемыми:
Отмена действия браузера при mousedown/selectstart отменяет выделение при клике, но не запрещает его полностью.
Если пользователь всё же хочет выделить текстовое содержимое элемента, то он может сделать это.
Достаточно начать выделение (зажать кнопку мыши) не на самом элементе, а рядом с ним. Ведь там отмены не произойдёт, выделение начнётся, и дальше можно передвинуть мышь уже на элемент.
Способ 2: снятие выделения постфактум
Вместо предотвращения выделения, можно его снять в обработчике события, после того, как оно уже произошло.
Для этого мы используем методы работы с выделением, которые описаны в отдельной главе Выделение: Range, TextRange и Selection. Здесь нам понадобится всего лишь одна функция clearSelection , которая будет снимать выделение.
Пример со снятием выделения при двойном клике на элемент списка:
У этого подхода есть две особенности, на которые стоит обратить внимание:
- Выделение всё же производится, но тут же снимается. Это выглядит как мигание и не очень красиво.
- Выделение при помощи передвижения зажатой мыши всё ещё работает, так что посетитель имеет возможность выделить содержимое элемента.
Способ 3: свойство user-select
Существует нестандартное CSS-свойство user-select , которое делает элемент невыделяемым.
Оно когда-то планировалось в стандарте CSS3, потом от него отказались, но поддержка в браузерах уже была сделана и потому осталась.
Это свойство работает (с префиксом) везде, кроме IE9-:
Строка до.. Этот текст нельзя выделить (кроме IE9-) .. Строка после
IE9-: атрибут unselectable=«on»
В IE9- нет user-select , но есть атрибут unselectable.
Он отменяет выделение, но у него есть особенности:
- Во-первых, невыделяемость не наследуется. То есть, невыделяемость родителя не делает невыделяемыми детей.
- Во-вторых, текст, в отличие от user-select , всё равно можно выделить, если начать выделение не на самом элементе, а рядом с ним.
Этот текст невыделяем в IE, кроме дочерних элементов
Левая часть текста в IE не выделяется при двойном клике. Правую часть ( em ) можно выделить, т.к. на ней нет атрибута unselectable .
Итого
Для отмены выделения есть несколько способов:
- CSS-свойство user-select – везде кроме IE9- (нужен префикс, нестандарт).
- Атрибут unselectable=»on» – работает для любых IE (должен быть у всех потомков)
- Отмена действий на mousedown и selectstart :
elem.onmousedown = elem.onselectstart = function() < return false; >;
Это зависит от задач и вашего удобства, а также конкретного случая. Все описанные способы работают.
Недостаток user-select – в том, что посетитель теряет возможность скопировать текст. А что, если он захочет именно это сделать?
В любом случае эти способы не предназначены для защиты от выделения-и-копирования.
Если уж хочется запретить копирование – можно использовать событие oncopy :
Уважаемый копирователь, почему-то автор хочет заставить вас покопаться в исходном коде этой страницы. Если вы знаете JS или HTML, то скопировать текст не составит для вас проблемы, ну а если нет, то увы.
How do websites block selecting text and how do I unblock that?
There’s a website (example) that somehow blocks selecting text. Also it blocks Ctrl + A to select everything, there is also no “Copy” in the popup menu. What I have tried: Some sites use JavaScript to block selection. So I disabled all JavaScript sources in no-script addon in Firefox. I tried the same site in Google Chrome with the Script Safe addon. Made sure that everything is blocked, still can’t select text. Mousepointer remains an arrow and not a text cursor also on the whole site. Used about:config to disable JavaScript completely in Firefox. Still no effect. I read that some sites use DIVs with the style display:block so I used Inspect to examine the styles of the site. There is not one mention of «block» on the whole website, not in embedded CSS nor in object style=-attributes. The text is not an image or flash or some HTML5 canvas ect. Everything is within DIV and P tags but no style was found that might block the text selection. How can the website still block any selection of text? Not to mention why browsers support such behaviours at all. I just want to use a selected word or sentence and want to search google for it using right mouse click. It’s pretty annoying when a website does such things and forces me to type technical terms and names into google by hand. It disturbs my workflow.
@Xen2050 Mostly I don’t care about copying text. I just love the ability to mark phrases and terms and search for it on Google with just a click of the mouse (doubleclick word, rightclick «Search Google. «). I could go into the source (if it’s clean source at all) and scan for the word, copy it, paste in Google but well. as said this is just an annoyance. Some1 who wants to copy your website text can do it anyhow but someone who just wants a comfortable workflow gets hindered.
Can we just take a moment and sympathize for all the delusional web developers out there who think this is a good security measure?
@MCMastery Or worse, the developers who know it’s terrible but are told they have to do it anyway. Most of the time they are worried about people stealing content. Then you’ve got sites like SO who are getting scraped/stolen from all the time. but commercially viable. Turns out alienating your userbase is bad for business. Who would have thought?!
@MCMastery — the goal, as usual, is not to be faster than the dinosaur. The goal is to be faster than the dude next to you. Just as a goal of a lock isn’t to defeat a burglar, it’s to introduce more friction for them to go burgle someone else. Or in other words, the goal of the measure is not to introduce bulletproof security; it’s to introduce enough friction to (a) deter casual copier and (b) make a less casual copier more interested in less-work-required-to-copy alternative sites.
MozUserSelect style property | webkitUserSelect style property
In Internet Explorer and Opera, use the unselectable property for similar functionality.
In Internet Explorer, Google Chrome and Safari, there is another possibility to make an element unselectable. If the onselectstart event is canceled, the selection process does not start.
For further details, please see the unselectable property and the onselectstart event.
Syntax:
Possible values:
The element’s contents can only be selected as a whole. |
None of the element’s contents can be selected. |
The element’s contents can only be selected as a whole. |
One element at a time may be selected. |
One or more elements at a time may be selected. |
Takes the value of this property from the computed style of the parent element. |
None of the element’s contents can be selected. |
Default. Only the element’s text content may be selected. |
The element’s contents may be selected. |
Example HTML code 1:
This example illustrates the use of the -moz-user-select and the -webkit-user-select properties:
head> style> .unselectable -moz-user-select: none; -webkit-user-select: none; > style> head> body> div class="unselectable">The user is not able to select this text in Firefox, Google Chrome and Safari.div> body>
Example HTML code 2:
head> style> .unselectable -moz-user-select: none; -webkit-user-select: none; > style> head> body> div class="unselectable" unselectable="on"> The user is not able to select this text in Firefox, Google Chrome and Safari. In Internet Explorer and Opera, it is selectable only if the selection starts outside. div> body>
Example HTML code 3:
This example uses the MozUserSelect and webkitUserSelect properties to change the selectable state of an element. For a cross-browser solution, please see the next example.
head> script type="text/javascript"> function ChangeUserSelect (selectTag) // Returns the index of the selected option var whichSelected = selectTag.selectedIndex; // Returns the text of the selected option var selectState = selectTag.options[whichSelected].text; var div = document.getElementById ("myDiv"); if ('MozUserSelect' in div.style) < div.style.MozUserSelect = selectState; > else if ('webkitUserSelect' in div.style) < div.style.webkitUserSelect = selectState; > else alert ("Your browser doesn't support this example!"); > > script> head> body> div id="myDiv"> Select this text or button>this buttonbutton> or a>this anchor elementa> and b>changeb> the state of i>MozUserSelecti> with the select field. div> select onchange="ChangeUserSelect (this);" size="9"> option selected="selected" />-moz-all option />-moz-none option />all option />element option />elements option />inherit option />none option />text option />toggle select> body>
Example HTML code 4:
head> style> #mySpan -moz-user-select:none; -webkit-user-select:none; > style> script type="text/javascript"> function ToggleSelState () var span = document.getElementById ("mySpan"); if ('unselectable' in span) // Internet Explorer, Opera span.unselectable = !span.unselectable; > else if (window.getComputedStyle) var style = window.getComputedStyle (span, null); if ('MozUserSelect' in style) // Firefox span.style.MozUserSelect = (style.MozUserSelect == "none") ? "text" : "none"; > else if ('webkitUserSelect' in style) // Google Chrome and Safari span.style.webkitUserSelect = (style.webkitUserSelect == "none") ? "text" : "none"; > else alert ("Your browser doesn't support this example!"); > > > else alert ("Your browser doesn't support this example!"); > > > script> head> body> span id="mySpan" unselectable="on">Select this text.span> br />br />br /> button onclick="ToggleSelState ();">Change selectable state!button> body>