diff options
Diffstat (limited to 'files/ru/web/html/element/input/button/index.html')
-rw-r--r-- | files/ru/web/html/element/input/button/index.html | 345 |
1 files changed, 345 insertions, 0 deletions
diff --git a/files/ru/web/html/element/input/button/index.html b/files/ru/web/html/element/input/button/index.html new file mode 100644 index 0000000000..984fa13988 --- /dev/null +++ b/files/ru/web/html/element/input/button/index.html @@ -0,0 +1,345 @@ +--- +title: <input type="button"> +slug: Web/HTML/Element/Input/button +tags: + - HTML формы + - Формы + - Элемент Input +translation_of: Web/HTML/Element/input/button +--- +<div>{{HTMLRef}}</div> + +<p><span class="seoSummary">Элемент {{HTMLElement("input")}} с типом <strong><code>button</code></strong> отображаются как простые кнопки, которые можно запрограммировать для управления пользовательскими функциями в любом месте веб-страницы, например, назначить функцию обработки события (обычно для события {{event("click")}}).</span></p> + +<div>{{EmbedInteractiveExample("pages/tabbed/input-button.html", "tabbed-shorter")}}</div> + + + +<div class="note"> +<p><strong>Заметка</strong>: Хотя элементы <code><input></code> с типом <code>button</code> по-прежнему являются абсолютно корректными в HTML, новый элемент {{HTMLElement("button")}} теперь является предпочтительным способом создания кнопок. Учитывая, что текст элемента {{HTMLElement("button")}} вставлен между открывающим и закрывающим тегами, вы можете включить в тег HTML, даже изображения.</p> +</div> + +<table class="properties"> + <tbody> + <tr> + <td><strong>{{anch("Значение")}}</strong></td> + <td>{{domxref("DOMString")}} используется в качестве метки кнопки</td> + </tr> + <tr> + <td><strong>Событие</strong></td> + <td>{{event("click")}}</td> + </tr> + <tr> + <td><strong>Поддерживаемые общие атрибуты</strong></td> + <td>{{htmlattrxref("type", "input")}} и {{htmlattrxref("value", "input")}}</td> + </tr> + <tr> + <td><strong>Атрибуты IDL</strong></td> + <td><code>value</code></td> + </tr> + <tr> + <td><strong>Методы</strong></td> + <td>None</td> + </tr> + </tbody> +</table> + +<h2 id="Значение">Значение</h2> + +<p>Атрибут значения элементов <code><input type="button"></code> elements' {{htmlattrxref("value", "input")}} содержит строку {{domxref("DOMString")}} , которая используется в качестве метки кнопки.</p> + +<div id="summary-example3"> +<pre class="brush: html"><input type="button" value="Нажми на меня"></pre> +</div> + +<p>{{EmbedLiveSample("summary-example3", 650, 30)}}</p> + +<p>Если вы не укажете <code>value</code>, вы получите пустую кнопку:</p> + +<div id="summary-example1"> +<pre class="brush: html"><input type="button"></pre> +</div> + +<p>{{EmbedLiveSample("summary-example1", 650, 30)}}</p> + +<h2 id="Использование_кнопок">Использование кнопок</h2> + +<p>Элементы <code><input type="button"></code> не имеют поведения по умолчанию (их двоюродные братья, <code><a href="/en-US/docs/Web/HTML/Element/input/submit"><input type="submit"></a></code> и <code><a href="/en-US/docs/Web/HTML/Element/input/reset"><input type="reset"></a></code> используются для отправки и сброса форм соответственно). Чтобы кнопки делали что-либо, вы должны написать код JavaScript для выполнения работы.</p> + +<h3 id="Простая_кнопка">Простая кнопка</h3> + +<p>Мы начнем с создания простой кнопки с обработчиком события {{event("click")}} , который запускает наш компьютер (ну, он переключает <code>value</code> кнопки и текстовое содержимое следующего абзаца):</p> + +<pre class="brush: html"><form> + <input type="button" value="Запустить ПК"> +</form> +<p>ПК выключен.</p></pre> + +<pre class="brush: js">const button = document.querySelector('input'); +const paragraph = document.querySelector('p'); + +button.addEventListener('click', updateButton); + +function updateButton() { + if (button.value === 'Запустить ПК') { + button.value = 'Выключить ПК'; + paragraph.textContent = 'ПК запущен!'; + } else { + button.value = 'Запустить ПК'; + paragraph.textContent = 'ПК выключен.'; + } +}</pre> + +<p>Сценарий получает ссылку на объект {{domxref("HTMLInputElement")}}, представляющий <code><input></code> в DOM, сохраняя этот параметр в переменной <code>button</code>. Затем {{domxref("EventTarget.addEventListener", "addEventListener()")}} используется для установки функции, которая будет запускаться, когда на кнопке происходят события {{event("click")}}.</p> + +<p>{{EmbedLiveSample("Простая_кнопка", 650, 100)}}</p> + +<h3 id="Добавление_сочетаний_клавиш_на_кнопки">Добавление сочетаний клавиш на кнопки</h3> + +<p>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 {{HTMLElement("input")}} for which it makes sense — you use the {{htmlattrxref("accesskey")}} global attribute.</p> + +<p>In this example, <kbd>s</kbd> is specified as the access key (you'll need to press <kbd>s</kbd> plus the particular modifier keys for your browser/OS combination; see <a href="/en-US/docs/Web/HTML/Global_attributes/accesskey">accesskey</a> for a useful list of those).</p> + +<div id="accesskey-example1"> +<pre class="brush: html"><form> + <input type="button" value="Start machine" accesskey="s"> +</form> +<p>The machine is stopped.</p> +</pre> +</div> + +<div class="hidden"> +<pre class="brush: js">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.'; + } +}</pre> +</div> + +<p>{{EmbedLiveSample("Adding_keyboard_shortcuts_to_buttons", 650, 100)}}</p> + +<div class="note"> +<p><strong>Note</strong>: 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 intefere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).</p> +</div> + +<h3 id="Disabling_and_enabling_a_button">Disabling and enabling a button</h3> + +<p>To disable a button, simply specify the {{htmlattrxref("disabled")}} global attribute on it, like so:</p> + +<div id="disable-example1"> +<pre class="brush: html"><input type="button" value="Disable me" disabled></pre> +</div> + +<p>You can enable and disable buttons at run time by simply setting <code>disabled</code> to <code>true</code> or <code>false</code>. In this example our button starts off enabled, but if you press it, it is disabled using <code>button.disabled = true</code>. A {{domxref("WindowTimers.setTimeout","setTimeout()")}} function is then used to reset the button back to its enabled state after two seconds.</p> + +<div class="hidden"> +<h6 id="Hidden_code_1">Hidden code 1</h6> + +<pre class="brush: html"><input type="button" value="Enabled"></pre> + +<pre class="brush: js">const button = document.querySelector('input'); + +button.addEventListener('click', disableButton); + +function disableButton() { + button.disabled = true; + button.value = 'Disabled'; + window.setTimeout(function() { + button.disabled = false; + button.value = 'Enabled'; + }, 2000); +}</pre> +</div> + +<p>{{EmbedLiveSample("Hidden_code_1", 650, 60)}}</p> + +<p>If the <code>disabled</code> attribute isn't specified, the button inherits its <code>disabled</code> 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 {{HTMLElement("fieldset")}} element, and then setting <code>disabled</code> on the container.</p> + +<p>The example below shows this in action. This is very similar to the previous example, except that the <code>disabled</code> attribute is set on the <code><fieldset></code> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.</p> + +<div class="hidden"> +<h6 id="Hidden_code_2">Hidden code 2</h6> + +<pre class="brush: html"><fieldset> + <legend>Button group</legend> + <input type="button" value="Button 1"> + <input type="button" value="Button 2"> + <input type="button" value="Button 3"> +</fieldset></pre> + +<pre class="brush: js">const button = document.querySelector('input'); +const fieldset = document.querySelector('fieldset'); + +button.addEventListener('click', disableButton); + +function disableButton() { + fieldset.disabled = true; + window.setTimeout(function() { + fieldset.disabled = false; + }, 2000); +}</pre> +</div> + +<p>{{EmbedLiveSample("Hidden_code_2", 650, 60)}}</p> + +<div class="note"> +<p><strong>Note</strong>: Firefox will, unlike other browsers, by default, <a href="http://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing">persist the dynamic disabled state</a> of a {{HTMLElement("button")}} across page loads. Use the {{htmlattrxref("autocomplete","button")}} attribute to control this feature.</p> +</div> + +<h2 id="Validation">Validation</h2> + +<p>Buttons don't participate in constraint validation; they have no real value to be constrained.</p> + +<h2 id="Examples">Examples</h2> + +<p>The below example shows a very simple drawing app created using a {{htmlelement("canvas")}} element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas.</p> + +<pre class="brush: html"><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">30</span> + <input type="button" value="Clear canvas"> +</div> + +<canvas class="myCanvas"> + <p>Add suitable fallback here.</p> +</canvas></pre> + +<div class="hidden"> +<pre class="brush: css">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; +}</pre> +</div> + +<pre class="brush: js">var canvas = document.querySelector('.myCanvas'); +var width = canvas.width = window.innerWidth; +var height = canvas.height = window.innerHeight-85; +var ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'rgb(0,0,0)'; +ctx.fillRect(0,0,width,height); + +var colorPicker = document.querySelector('input[type="color"]'); +var sizePicker = document.querySelector('input[type="range"]'); +var output = document.querySelector('.output'); +var clearBtn = document.querySelector('input[type="button"]'); + +// covert degrees to radians +function degToRad(degrees) { + return degrees * Math.PI / 180; +}; + +// update sizepicker output value + +sizePicker.oninput = function() { + output.textContent = sizePicker.value; +} + +// store mouse pointer coordinates, and whether the button is pressed +var curX; +var curY; +var pressed = false; + +// update mouse pointer coordinates +document.onmousemove = function(e) { + curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); + curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); +} + +canvas.onmousedown = function() { + pressed = true; +}; + +canvas.onmouseup = function() { + pressed = false; +} + +clearBtn.onclick = function() { + 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();</pre> + +<p>{{EmbedLiveSample("Examples", '100%', 600)}}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comments</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'forms.html#button-state-(type=button)', '<input type="button">')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#button-state-(type=button)', '<input type="button">')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("html.elements.input.input-button")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it.</li> + <li>The more modern {{HTMLElement("button")}} element.</li> + <li><a href="/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Compatibility of CSS properties</a></li> +</ul> |