- :disabled
- Примеры
- Пример селекторов
- Пример использования
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Можно ли сделать внутри блока ссылки некликабельный элемент?
- :disabled , :enabled
- Кратко
- Пример
- Как пишется
- Как понять
- Подсказки
- На практике
- Алёна Батицкая советует
- 5 Ways to Disable Elements In An HTML DIV
- QUICK SLIDES
- TABLE OF CONTENTS
- DOWNLOAD & NOTES
- QUICK NOTES
- EXAMPLE CODE DOWNLOAD
- HOW TO DISABLE
- METHOD 1) DISABLE FORM
- METHOD 2) HIDE IT
- METHOD 3) COVER ANOTHER DIV OVER IT
- METHOD 4) CSS POINTER EVENT
- METHOD 5) DISABLE TEXT HIGHLIGHT
- USEFUL BITS & LINKS
- LINKS & REFERENCES
- THE END
- Не активная кнопка с помощью disabled
:disabled
CSS псевдокласс :disabled находит любой отключённый элемент. Элемент отключён, если не может быть активирован (например, его нельзя выбрать, нажать на него или ввести текст) или получить фокус. У элемента также есть включённое состояние, когда его можно активировать или сфокусировать.
Примеры
Пример селекторов
Выберет все отключённые поля ввода
Найдёт все отключённые select элементы с классом country
Пример использования
input[type="text"]:disabled background: #ccc; >
Применим к этому HTML5 фрагменту:
form action="#"> fieldset> legend>Адрес доставкиlegend> input type="text" placeholder="Имя"> input type="text" placeholder="Адрес"> input type="text" placeholder="Почтовый индекс"> fieldset> fieldset id="billing"> legend>Адрес оплатыlegend> label for="billing_is_shipping">Такой же как адрес доставки:label> input type="checkbox" onchange="javascript:toggleBilling()" checked> br /> input type="text" placeholder="Имя" disabled> input type="text" placeholder="Адрес" disabled> input type="text" placeholder="Почтовый индекс" disabled> fieldset> form>
Добавим немного javascript:
function toggleBilling() var billingItems = document.querySelectorAll('#billing input[type="text"]'); for (var i = 0; i billingItems.length; i++) billingItems[i].disabled = !billingItems[i].disabled; > >
Результатом будет отключение всех полей в группе адреса оплаты и окраска их в серый цвет.
Спецификации
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 14 февр. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Можно ли сделать внутри блока ссылки некликабельный элемент?
Код здесь
Нужно сделать, чтобы спаны с классами type-of-work__item-price и type-of-work__item-time были не кликабельны.
pointer-events: none;
не помогает.
Может быть есть еще идеи?
Евгений Эта поправка пришла позже, не хотелось менять структуру. К тому же кликабельным должно быть и изображение (Там картинки не подгрузились)
Можно. Например я такое часто использую, если в адаптивной верстке мне необходимо на ссылку меню справа повесить span, при нажатии на который будет отменено свойства перехода по ссылке и произойдет выпадение подменю. Но делаю я такое исключительно при адаптиве, причем span помещаю скриптом тоже. Делаю это вот таким образом:
//Проверка на наличие подменю у левого меню. В случае нахождения добавляем "стрелку" для выпадающего меню $('.left-menu__list .left-menu__item').append( function(indx, val)< if($(this).find('.left-menu__list').length != 0) return '›'; else return ''; >); //Окончание секции "Проверка на наличие подменю у левого меню. В случае нахождения добавляем "стрелку" для выпадающего меню" //Раскрытие меню при нажатии на "стрелку" $('.arrow').click(function()< $(this).toggleClass('arrow-switch'); $(this).parents('.left-menu__item').find('.left-menu__list').toggleClass('left-menu__list--open'); >); //Окончание секции "Раскрытие меню при нажатии на "стрелку"
.left-menu__list < max-height: 0; -webkit-transition: 800ms ease all; transition: 800ms ease all; >.left-menu__list--open
:disabled , :enabled
Эта кнопка серая. Она не доступна для клика. Как написать селектор на основе состояния элемента?
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
Псевдоклассы :disabled и :enabled помогают стилизовать интерактивные элементы — на которые можно и нельзя нажать.
Легко применяются к любым элементам, которым можно задать атрибут disabled : , , , , , , , и .
Пример
Скопировать ссылку «Пример» Скопировано
Часто требуется, чтобы на кнопку отправки формы нельзя было нажать, пока не заполнены все поля этой формы. Проще всего заблокировать кнопку атрибутом disabled . Но недостаточно просто указать его в HTML, нужно ещё и при помощи оформления показать пользователю, что кнопка не активна. Как раз для этого нам пригодится псевдокласс :disabled .
Кнопка будет полупрозрачной:
button:disabled opacity: 0.5;>
button:disabled opacity: 0.5; >
Псевдокласс :enabled , наоборот, поможет стилизовать все доступные для взаимодействия элементы. По факту его чаще всего не указывают, потому что записи с ним и без него, как правило, равноценны: .input = .input : enabled .
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Любому селектору, указывающему на интерактивный элемент, дописываем двоеточие и указываем одно из ключевых слов: enabled или disabled .
Как понять
Скопировать ссылку «Как понять» Скопировано
Браузер ориентируется на атрибут disabled и, в зависимости от его наличия или отсутствия, добавляет элементу состояние enabled — доступен, или disabled — недоступен.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Даже если дизайнер забыл про неактивное состояние, обязательно прописывайте его в стилях, чуть приглушая фоновый цвет или делая элемент полупрозрачным — чтобы пользователь точно знал, что с этим элементом взаимодействовать нельзя.
💡 enabled чаще всего не используется, потому что все интерактивные элементы по умолчанию доступны (включены). Это значит, что прописав стили для селектора .input , вы закрываете сценарий с активным элементом.
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 «Выключать» взаимодействие с кнопками или другими элементами формы удобнее именно атрибутом disabled , потому что он сразу же отключает возможность нажать на этот элемент без дополнительных стилей. И, ориентируясь на него, гораздо удобнее прописывать стили для неактивных элементов, используя псевдокласс disabled .
Код для кнопки из моего последнего проекта:
Стили для активной кнопки в обычном состоянии:
.additional-btn padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none;>
.additional-btn padding: 2rem 3rem; border: 1px solid currentColor; font-family: inherit; font-size: 1.6rem; color: #FF6650; text-decoration: none; background-color: transparent; transition: border 0.3s, color 0.3s; cursor: pointer; user-select: none; >
Стили для кнопки при наведении курсора или клике:
.additional-btn:active,.additional-btn:hover color: #FF5050; transition: none;>
.additional-btn:active, .additional-btn:hover color: #FF5050; transition: none; >
Стили для кнопки, когда она неактивна:
.additional-btn:disabled cursor: default; color: #A44234;>
.additional-btn:disabled cursor: default; color: #A44234; >
5 Ways to Disable Elements In An HTML DIV
Welcome to a tutorial on how to disable elements inside an HTML DIV.
- var all = document.querySelectorAll(«#container select, #container input, #container textarea, #container button»);
- for (let el of all)
Otherwise, when it comes to “disabling a DIV”, that could literally mean anything. From disabling a form placed inside it, to stopping videos, to preventing copy-paste, preventing text highlight, to removing on click events – There is no “universal way to disable everything”.
Just how do we “blanket disable” all of these then? Well, there are still a couple of tricks and alternatives – Let us walk through some examples in this guide, read on!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
HOW TO DISABLE
All right, let us now get into the various ways to disable an entire div in HTML.
METHOD 1) DISABLE FORM
Name: Email: Random Story: Cate or Doge: // (B1) GET ALL FORM ELEMENTS var all = document.querySelectorAll("#container select, #container input, #container textarea, #container button"); // (B2) DISABLE ALL for (let el of all) < el.disabled = true; >// (B3) TO ENABLE // for (let el of allform)
- Grab all the form elements ( ) using document.querySelectorAll() .
- Then disable them accordingly with ELEMENT.disabled = true .
METHOD 2) HIDE IT
HELLO WORLD! My name na Uvuvwevwevwe Onyetenyevwe Ugwemubwem Ossas.
This is not really “disable”, but to “hide”. If we don’t have any good use for a particular section, then why add to the confusion by showing it? Just hide the and show it only when necessary.
METHOD 3) COVER ANOTHER DIV OVER IT
/* (A1) SET RELATIVE POSITION ON CONTAINER */ #container < position: relative; >/* (A2) OVERLAY OVER CONTAINER */ #overlay CONTENTS INSIDE
- We can cover an extra layer of over the container .
- This will block the bottom , effectively preventing all kinds of interactions with it – Forms, videos, clicks, highlights, etc…
- It is done using just some simple CSS.
- The container must be set to relative or absolute position first.
- To place the overlay over the container – position:absolute; top:0; width:100%; height:100%;
METHOD 4) CSS POINTER EVENT
#container
CONTENTS INSIDEYep, pointer-events: none is all it takes to disable all the button clicks inside a container. Take note this will not work on ancient browsers that do not support pointer-events though.
METHOD 5) DISABLE TEXT HIGHLIGHT
.nohighlight *::selection < background: none; >.nohighlight
RANDOM CONTENTSLorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sit amet volutpat diam.
RANDOM CONTENTS
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sit amet volutpat diam.
If you just want to disable the highlighting of text to prevent people from copying, simply use CSS user-select: none to do it. .nohighlight *::selection < background: none >is kind of an extra to not show highlight background colors.
USEFUL BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Не активная кнопка с помощью disabled
HTML-CSS-JQUERY
В этой статье мы рассмотрим как сделать кнопку не активной, при не выполнении определенных условий в форме отправки данных на сайте. Напишем код для кнопки подтверждающей «Согласие на обработку персональных данных», данная тема сейчас востребована в связи с введение закона о «Персональных данных». То есть пока клиент при отправке формы не установит чекбокс напротив надписи «Согласие на обработку персональных данных», кнопка отправки будет не активна.
Зададим тегу значение disabled, которое задает не активность кнопки «Отправить». И немного украсим нашу кнопку и type «checkbox» с помощью CSS.
body < background-color: #1684af; color: #fff; >label < margin-bottom: 8px; font-size: 13px; >input[type=»checkbox»]:checked, input[type=»checkbox»]:not(:checked) < position: absolute; left: -9999px; >input[type=»checkbox»]:checked + label, input[type=»checkbox»]:not(:checked) + label < display: inline-block; position: relative; padding-left: 20px; line-height: 1; cursor: pointer; >input[type=»checkbox»]:checked + label:before, input[type=»checkbox»]:not(:checked) + label:before < content: ""; position: absolute; left: 0px; top: 0px; width: 12px; height: 12px; background-color: #ffffff; >input[type=»checkbox»]:checked + label:after, input[type=»checkbox»]:not(:checked) + label:after < content: ""; position: absolute; -webkit-transition: all 0.2s ease; -moz-transition: all 0.2s ease; -o-transition: all 0.2s ease; transition: all 0.2s ease; >input[type=»checkbox»]:checked + label:after, input[type=»checkbox»]:not(:checked) + label:after < left: 1px; top: 1px; width: 2px; height: 2px; border: 4px solid #F2622E; >input[type=»checkbox»]:not(:checked) + label:after < opacity: 0; >input[type=»checkbox»]:checked + label:after < opacity: 1; >.check-policy < font-size: 13px; >.btn < padding: 0.75em 1.75em; display: inline-block; line-height: 1; margin: 2em 0; color: #fff; background-color: #F2622E; border: none; >.btn:hover < cursor: pointer; >.btn:disabled, .btn:hover:disabled
А теперь добавим к input JS событие:
что бы при нажатии на строчку с «Согласие на обработку персональных данных» кнопка «Отправить» стала активной.
Посмотреть как это работает можно здесь: