- Как сделать кнопку в HTML
- А как же input?
- Как сделать кнопку с иконкой
- С помощью тега
- Добавить инлайн SVG в разметку
- Вставить фоном в CSS
- Материалы по теме
- Input button name css
- Button without a value
- Using buttons
- A simple button
- Adding keyboard shortcuts to buttons
- Disabling and enabling a button
- Setting the disabled attribute
- Inheriting the disabled state
- Validation
- Examples
- Technical summary
- Specifications
- input-button-name
- How to fix
- Example
- Fail
- Pass
- About this rule
- More examples
- Атрибут name
- Синтаксис
- Значения
- Значение по умолчанию
- Типы тегов
Как сделать кнопку в HTML
Для создания кнопок используется тег . Внутри него размещается текст или изображение, которые будут отображаться на кнопке. Например:
Чтобы задать кнопке имя, тип или состояние, нужно добавить атрибуты: name , disabled и type .
Атрибут name задаёт имя кнопки. Может использоваться для идентификации элемента в скриптах.
Атрибут disabled блокирует доступ к кнопке.
Атрибут type определяет тип кнопки. Ему задают одно из трёх значений:
button — значение по умолчанию. Означает, что элемент — обычная кнопка. Она может добавлять товары в корзину или избранное, переключать слайдеры или закрывать всплывающие окна.
submit задаётся кнопкам для отправки формы. Когда пользователь нажимает на кнопку с таким типом, браузер отправляет данные формы на сервер.
reset добавляется кнопкам сброса формы. Когда пользователь нажимает на такую кнопку, браузер возвращает значения всех полей формы к изначальным.
А как же input?
Создать кнопку можно и с помощью тега , если указать ему тип button :
Это рабочий способ. О нём надо знать, ведь вы можете встретить его в проектах. Но самим так делать не стоит. У кнопок, созданных на инпуте, есть ограничения: сложно управлять размерами и положением изображений, а также нет псевдоэлементов. Поэтому оставьте для создания элементов формы, таких как текстовые поля, радиокнопки или чекбоксы. А кнопки верстайте с помощью .
Как сделать кнопку с иконкой
Посмотрим три способа создания кнопки с иконкой.
С помощью тега
Способ подойдёт для контентных изображений.
Так вы можете добавлять кнопки с эмодзи, лайками, дизлайками или чем-то ещё. Иконке нужно обязательно задавать размеры, чтобы кнопка зарезервировала место и не прыгала, когда загрузится иконка.
Добавить инлайн SVG в разметку
Способ подойдёт, если изображение меняет состояния, как здесь:
Код простой: пишем тег и добавляем в него код SVG-изображения.
Вставить фоном в CSS
Способ подойдёт, если иконка играет декоративную роль и не меняется при наведении или клике на кнопку. Например, в таких случаях:
Как добавить иконку в кнопку:
Какой способ выбрать — зависит от ваших задач и особенностей проекта. Вы также можете использовать разные методы в рамках одного проекта. Например, часть кнопок сделать со встроенным в разметку SVG, а часть — с фоновым изображением.
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Input button name css
An elements’ value attribute contains a string that is used as the button’s label.
input type="button" value="Click Me" />
Button without a value
If you don’t specify a value , you get an empty button:
Using buttons
A simple button
We’ll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph):
form> input type="button" value="Start machine" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
The script gets a reference to the HTMLInputElement object representing the in the DOM, saving this reference in the variable button . addEventListener() is then used to establish a function that will be run when click events occur on the button.
Adding keyboard shortcuts to buttons
Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the accesskey global attribute.
In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).
form> input type="button" value="Start machine" accesskey="s" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).
Disabling and enabling a button
To disable a button, specify the disabled global attribute on it, like so:
input type="button" value="Disable me" disabled />
Setting the disabled attribute
You can enable and disable buttons at run time by setting disabled to true or false . In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true . A setTimeout() function is then used to reset the button back to its enabled state after two seconds.
input type="button" value="Enabled" />
const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton() button.disabled = true; button.value = "Disabled"; setTimeout(() => button.disabled = false; button.value = "Enabled"; >, 2000); >
Inheriting the disabled state
If the disabled attribute isn’t specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting disabled on the container.
The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.
fieldset> legend>Button grouplegend> input type="button" value="Button 1" /> input type="button" value="Button 2" /> input type="button" value="Button 3" /> fieldset>
const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton() fieldset.disabled = true; setTimeout(() => fieldset.disabled = false; >, 2000); >
Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the autocomplete attribute to control this feature.
Validation
Buttons don’t participate in constraint validation; they have no real value to be constrained.
Examples
div class="toolbar"> input type="color" aria-label="select pen color" /> input type="range" min="2" max="50" value="30" aria-label="select pen size" />span class="output">30span> input type="button" value="Clear canvas" /> div> canvas class="myCanvas"> p>Add suitable fallback here.p> canvas>
body background: #ccc; margin: 0; overflow: hidden; > .toolbar background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"] width: 90%; margin: 0 auto; display: block; > input[type="range"] width: 70%; > span position: relative; bottom: 5px; >
const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) return (degrees * Math.PI) / 180; > // update sizepicker output value sizePicker.oninput = () => output.textContent = sizePicker.value; >; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) => curX = e.pageX; curY = e.pageY; >; canvas.onmousedown = () => pressed = true; >; canvas.onmouseup = () => pressed = false; >; clearBtn.onclick = () => ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); >; function draw() if (pressed) ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); > requestAnimationFrame(draw); > draw();
Technical summary
Specifications
input-button-name
An input button is an element whose type is button , reset , or submit . An accessible name is a word or phrase coded in a way that assistive technologies can associate it with a specific user interface object. Assistive technologies can then refer to the object by name, not just by type. When an input button doesn’t have an accessible name, people who use assistive technologies have no way of knowing its specific purpose.
How to fix
- Non-empty value attribute
- No value attribute (applies only if type is submit or reset ; causes the type value to be reported as the accessible name)
- aria-label attribute
Example
Fail
CSS (not shown) is used to display an image on this input button. People with good vision can infer the button’s purpose from the image. However, because the button doesn’t have an accessible name, assistive technology users can’t determine its purpose.
Pass
An aria-label attribute provides an accessible name for the input button. Everyone can tell what the button does.
About this rule
This rule passes if ANY of the following is true:
- Element has a non-empty aria-label attribute
- Element has an aria-labelledby attribute that references elements that are visible to screen readers
- Element has a non-empty title attribute
- Element has a non-empty value attribute
- Element with type submit or reset does not have a value attribute
- Element’s default semantics were overridden with role=»presentation» or role=»none»
Use caution when applying role=»presentation» or role=»none» to an input button. These roles instruct assistive technologies to disregard the element’s implicit role without hiding its content from users. If an input button has inner text, adding a role of presentation or none will cause it to be reported to users as a text string with no semantic context. For more information, see Using ARIA: Use of Role=presentation or Role=none.
More examples
Understanding Success Criterion 4.1.2: Name, Role, Value
Атрибут name
Определяет уникальное имя кнопки. Как правило, это имя используется при отправке значения кнопки на сервер или для доступа к кнопке через скрипты.
Синтаксис
Значения
В качестве имени используется набор символов, включая числа и буквы. JavaScript чувствителен к регистру, поэтому при обращении к элементу по имени соблюдайте ту же форму написания, что и в атрибуте name .
Значение по умолчанию
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Типы тегов
HTML5
Блочные элементы
Строчные элементы
Универсальные элементы
Нестандартные теги
Осуждаемые теги
Видео
Документ
Звук
Изображения
Объекты
Скрипты
Списки
Ссылки
Таблицы
Текст
Форматирование
Формы
Фреймы