Css input not active

:disabled¶

Псевдо-класс :disabled находит любой отключенный элемент.

Элемент отключен, если не может быть активирован (например, его нельзя выбрать, нажать на него или ввести текст) или получить фокус. У элемента также есть включенное состояние, когда его можно активировать или сфокусировать.

Синтаксис¶

/* Selects any disabled */ input:disabled  background: #ccc; > 

Спецификации¶

Примеры¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
form action="#"> fieldset id="shipping"> legend>Shipping addresslegend> input type="text" placeholder="Name" /> input type="text" placeholder="Address" /> input type="text" placeholder="Zip Code" /> fieldset> br /> fieldset id="billing"> legend>Billing addresslegend> label for="billing_is_shipping">Same as shipping address:label> input type="checkbox" id="billing-checkbox" checked /> br /> input type="text" placeholder="Name" disabled /> input type="text" placeholder="Address" disabled /> input type="text" placeholder="Zip Code" disabled /> fieldset> form> 
input[type='text']:disabled  background: #ccc; > 
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Wait for the page to finish loading document.addEventListener( 'DOMContentLoaded', function()  // Attach `change` event listener to checkbox document.getElementById('billing-checkbox').onchange = toggleBilling >, false ) function toggleBilling()  // Select the billing text fields var billingItems = document.querySelectorAll('#billing input[type="text"]') // Toggle the billing text fields for (var i = 0; i  billingItems.length; i++)  billingItems[i].disabled = !billingItems[i].disabled > > 

Источник

:disabled

The :disabled CSS pseudo-class represents any disabled element. An element is disabled if it can’t be activated (selected, clicked on, typed into, etc.) or accept focus. The element also has an enabled state, in which it can be activated or accept focus.

Try it

Syntax

Examples

This example shows a basic shipping form. It uses the JavaScript change event to let the user enable/disable the billing fields.

HTML

form action="#"> fieldset id="shipping"> legend>Shipping addresslegend> input type="text" placeholder="Name" /> input type="text" placeholder="Address" /> input type="text" placeholder="Zip Code" /> fieldset> br /> fieldset id="billing"> legend>Billing addresslegend> label for="billing-checkbox">Same as shipping address:label> input type="checkbox" id="billing-checkbox" checked /> br /> input type="text" placeholder="Name" disabled /> input type="text" placeholder="Address" disabled /> input type="text" placeholder="Zip Code" disabled /> fieldset> form> 

CSS

input[type="text"]:disabled  background: #ccc; > 

JavaScript

// Wait for the page to finish loading document.addEventListener( "DOMContentLoaded", () =>  // Attach `change` event listener to checkbox document.getElementById("billing-checkbox").onchange = toggleBilling; >, false, ); function toggleBilling()  // Select the billing text fields const billingItems = document.querySelectorAll('#billing input[type="text"]'); // Toggle the billing text fields billingItems.forEach((item) =>  item.disabled = !item.disabled; >); > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

: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; >      

Источник

How to Disable an Input Field Using CSS?

The input field is used to make forms and take input from the user. Users can fill the input field according to the input type. But sometimes, you must disable the input field to fulfil any precondition, such as selecting a checkbox. In that situation, you need to disable the input field.

In this guide, we will gain an understanding of how to disable the input field using CSS. So, Let’s begin!

How to Disable an Input Field Using CSS?

In CSS, events are disabled by using the “pointer-events” property. So, first, learn about the pointer-events property.

What is “pointer-events” CSS Property?

The “pointer-events” control how the HTML elements respond or behave to the touch event, such as click or tap events, active or hover states, and whether the cursor is visible or not.

Syntax
The syntax of pointer-events is given as follows:

The above mention property takes two values, such as “auto” and “none”:

  • auto: It is used to perform default events.
  • none: It is utilized to disable events.

Head towards the given example.

Example 1: Adding an Input Field Using CSS

In this example, firstly, we will create a div and add a heading and input field to it. Then, set the input type as “text” and set its value as “Enter Your Name”.

After that, move to the CSS and style the div by setting its background color as “rgb(184, 146, 99)” and height as “150px”.

The output of the above-described code is given below. Here, we can see that our input field is currently active and is accepting the input from the user:

Now, move to the next part in which we use the value of the “pointer-events” property as “none”.

Example 2: Disabling an Input Field Using CSS

We will now use “input” to access the element added in the HTML file and set the value of pointer-events as “none”:

Once you implement the above-stated property “pointer-events” with “none” value, the text of the input field will be non-editable which indicates that our input field is disabled:

That’s it! We have explained the method of disabling the input field using CSS.

Conclusion

To disable an input field in an HTML, the “pointer-events” property of the CSS is used. To do so, add an input field, and set the value of pointer-events as “none” to disable the input field. In this guide, we explain the method of disabling an input field using CSS and provide an example of it.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Не активная кнопка с помощью disabled

Неактивная кнопка disabled

HTML-CSS-JQUERY

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

Кнопка отправить не активна при CSS disabled

 

Зададим тегу значение 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 событие:

 

что бы при нажатии на строчку с «Согласие на обработку персональных данных» кнопка «Отправить» стала активной.

Активная кнопка в HTML с помощью CSS

Посмотреть как это работает можно здесь:

Источник

Читайте также:  Алгоритм евклида питон рекурсия
Оцените статью