Css свойство user-select

Css user-select property

Select All… Then Select Some

While this works as expected, you may notice something annoying: it is impossible to select anything less than the entire code snippet. Wouldn’t it be nice if the first click selected all, but you could still click again and select just a portion? CSS can do this.

First, use to make the element holding the text focusable. This gives the CSS a way to know when the element has been clicked.

Then comes the CSS.

The idea is to have on the element initially, then switch to the “normal” after the element has focus so that text can be freely re-selected. The tricky part is the timing. Do the switch immediately upon focus and is gone before it has a chance to do its job. That’s where comes in.

Yes, is animatable! More specifically, it is discretely animatable, meaning there is no gradual interpolated animation, but rather an immediate cut from one state to another. Armed with this knowledge, we can use to delay the change in select behavior until 100ms after focus. Perfect.

Again, the “select all” bit doesn’t work on iOS. Meanwhile, desktop Safari keeps the text as “select all”. This trick seems to work fine elsewhere, though.

See the Pen Select All… Then Select Some by Will Boyd (@lonekorean) on CodePen.

Answer by London Summers

You can also use this to enforce that an entire element gets selection:,It’s worth noting that you can make areas of text selectable again using:,The comments are indeed unselectable, if I try to select them. Thanks for the trick!,The default value is auto, which makes selection happen normally as you expect. “Normally” is a bit complicated. It’s worth quoting from the spec here:

The property in CSS controls how the text in an element is allowed to be selected. For example, it can be used to make text unselectable.

You can also use this to enforce that an entire element gets selection:

Source: https://css-tricks.com/almanac/properties/u/user-select/

Разрешение копирования, но с указанием источника

Если Вы уверены в том, что поисковики быстро проиндексируют ваш оригинальный текст. Ваш сайт обновляется часто и страницы быстро появляются в индексе. И Вы допускаете возможность копирование Вашего контента, то конечно не стоит делать это просто так. Вполне логичным является требовать указания активной ссылки на вас, как первоисточник.

Для этого используйте скрипт, который автоматически будет добавлять ссылку на источник к копируемому тексту. Ну и не лишним будет написать в футере сайта о том, что копирование материалов разрешено только с указанием ссылки на них. Добавьте следующий скрипт, заменив «Название Вашего сайта»:

В результате при копировании любого текста с вашего сайта, к копии будет добавляться активная ссылка на страницу вашего сайта, с которой этот текст копируется:

Стоит отметить, что все описанные выше методы не являются 100% защитой и остановят не всех. Дело в том, что текст всегда можно вытащить из исходного кода страницы. И, к сожалению, с этим поделать уже ничего нельзя. Однако далеко не все имеют для этого достаточно навыков. Поэтому использование описанных методов защиты будет совсем не лишним.

Предыдущая запись Парсинг URL адресной строки
Следующая запись Передача метрики на другой аккаунт при смене владельца сайта

Способ 2: снятие выделения постфактум

Вместо предотвращения выделения, можно его снять в обработчике события, после того, как оно уже произошло.

Для этого мы используем методы работы с выделением, которые описаны в отдельной главе Выделение: Range, TextRange и Selection. Здесь нам понадобится всего лишь одна функция , которая будет снимать выделение.

Пример со снятием выделения при двойном клике на элемент списка:

У этого подхода есть две особенности, на которые стоит обратить внимание:

  • Выделение всё же производится, но тут же снимается. Это выглядит как мигание и не очень красиво.
  • Выделение при помощи передвижения зажатой мыши всё ещё работает, так что посетитель имеет возможность выделить содержимое элемента.

Предотвращение выделения текста

CSS можно использовать ещё и для того, чтобы сделать текст в элементе недоступным для выбора, т.е. запретить выделение текста.

Это плохая идея для основного текста, но будет полезно для элементов управления, которые можно быстро переключать или «гневно щелкать» в настольных браузерах, поскольку двойной щелчок вызывает выбор текста и подсветку его выделения – выглядеть немного странно и дико.

Проверить можно в следующей демонстрации

Обратите внимание, как переключатель слева становится подсвеченным при быстром нажатии, а переключатель справа – нет

See this code Preventing Text Highlights from Rage Clicking on x.xhtml.ru.

Этот метод также работает с виджетами раскрытия содержимого (HTML-элемент ) или фальшивыми кнопками – например, с обработчиком кликов на нём. Правда, использование настоящего элемента предпочтительнее не только с точки зрения семантики и доступности, но и потому, что текст в такой кнопке по умолчанию не может быть выделен, а это позволяет избежать проблемы с самого начала.

Syntax

The text of the element and its sub-elements is not selectable. Note that the object can contain these elements.

The used value of is determined as follows:

  • On the and pseudo elements, the used value is
  • If the element is an editable element, the used value is
  • Otherwise, if the used value of on the parent of this element is , the used value is
  • Otherwise, if the used value of on the parent of this element is , the used value is
  • Otherwise, the used value is
The text can be selected by the user.
The content of the element shall be selected atomically: If a selection would contain part of the element, then the selection must contain the entire element including all its descendants. If a double-click or context-click occurred in sub-elements, the highest ancestor with this value will be selected.
Enables selection to start within the element; however, the selection will be contained by the bounds of that element.
(IE-specific alias)
Same as . Supported only in Internet Explorer.

Note: CSS UI 4 renames to .

Способ 3: свойство user-select

Существует нестандартное CSS-свойство , которое делает элемент невыделяемым.

Оно когда-то планировалось в стандарте CSS3, потом от него отказались, но поддержка в браузерах уже была сделана и потому осталась.

Это свойство работает (с префиксом) везде, кроме IE9-:

Читайте на эту тему также Controlling Selection with CSS user-select.

В IE9- нет , но есть атрибут unselectable.

Он отменяет выделение, но у него есть особенности:

  1. Во-первых, невыделяемость не наследуется. То есть, невыделяемость родителя не делает невыделяемыми детей.
  2. Во-вторых, текст, в отличие от , всё равно можно выделить, если начать выделение не на самом элементе, а рядом с ним.

Левая часть текста в IE не выделяется при двойном клике. Правую часть () можно выделить, т.к. на ней нет атрибута .

В действии:

Этот текст невыделяем в IE, кроме дочерних элементов

CSS Свойства

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Answer by Braylon Sharp

When you give user-select property as text, user can select the text.,To disable text selection highlighting in Google Chrome browser using CSS just set -user-select CSS property to none.,To disable text selection highlighting in Safari browser using CSS just set -webkit-user-select CSS property to none.,To disable text selection highlighting in mozilla firefox browser using CSS just set -moz-user-select CSS property to none.

To disable the text selection in HTML we need to give user-select property value as none. Go through the below example to understand if further.

I have added disable-select class to the second div now we will add user-select css property

And no prefix is required for Google Chrome and Opera Browsers.

And we need add -moz prefix before user-select property for mozilla firefox Browser.

And we need add —webkit prefix before user-select property for Safari Browser.

To disable text selection highlighting in IOS Safari browser using CSS just set -webkit-touch-callout CSS property to none.

And we need add -ms prefix before user-select property for Safari Browser.

As explained above, when we give user-select property value as none to an HTML element we cannot select the text inside the element including it’s children element.

When you give user-select property as text, user can select the text.

When we give user-select property as all. Text inside the element is automatically selected on context click.

We will see all user-select options in one place.

And the corresponding CSS values are

Source: https://www.arungudelli.com/tutorial/css/disable-text-selection-in-html-using-user-select-css-property/

Выделить всё… Затем выделить часть

Хотя это работает должным образом, можно заметить кое-что неприятное: невозможно выбрать что-то отдельное, кроме всего фрагмента кода. Хорошо бы первым кликом выбрать всё, но оставить возможность кликнуть ещё раз и выбрать только часть. Это можно сделать, всё ещё, с помощью только CSS.

Во-первых, надо использовать , чтобы сделать HTML-элемент, содержащий текст, доступным для фокусировки. Это позволит CSS узнать о клике по HTML-элементу.

Теперь немного CSS.

Идея состоит в том, чтобы сначала установить для HTML-элемента CSS-свойство , а затем, когда фокус переместится на этот элемент, переключиться на «обычный» , чтобы текст можно было выбирать по частям. Выбор времени переключения – дело непростое. Если сделать переключение сразу после перемещения фокуса на элемент, то от не будет никакого эффекта, т.к. оно успеет сменить значение на . Поможет решить проблему .

CSS-свойство можно анимировать. Оно дискретно анимированное, это означает, что нет постепенной интерполированной анимации, по истечении указанного времени происходит немедленный переход от одного состояния к другому. Поэтому, можно использовать , чтобы отложить изменение поведения выделения текста до 100 миллисекунд после передачи фокуса HTML-элементу.

See this code Select All… Then Select Some on x.xhtml.ru.

Preventing Text Selection

You can also use CSS to make text in an element unselectable.

This is probably a bad idea for body text, but I’ve found it useful for controls that might be toggled quickly or “rage clicked” in desktop browsers, since double clicking causes text to be selected and highlighted, which can look a little weird sometimes.

See for yourself in the following demo. Notice how the toggle on the left becomes highlighted when rapidly clicked, while the one on the right doesn’t.

See the Pen Preventing Text Highlights from Rage Clicking by Will Boyd (@lonekorean) on CodePen.

This technique also works on disclosure widgets. Fake buttons — like a with a handler on it — are another candidate. Bear in mind that using a real is preferable, not only for semantics and accessibility, but also because text in a is unselectable by default, avoiding the issue to begin with.

CSS Справочники

CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы

CSS Свойства

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image
-source
border-image-width
border-left
border-left-color
border-left-style
border-left
-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row

grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style
-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index

Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: