Как вставить картинку в форму html
Перейти к содержимому

Как вставить картинку в форму html

  • автор:

<input type="image">

<input> elements of type image are used to create graphical submit buttons, i.e. submit buttons that take the form of an image rather than text.

Try it

Value

<input type=»image»> elements do not accept value attributes. The path to the image to be displayed is specified in the src attribute.

Additional attributes

In addition to the attributes shared by all <input> elements, image button inputs support the following attributes.

The alt attribute provides an alternate string to use as the button’s label if the image cannot be shown (due to error, a user agent that cannot or is configured not to show images, or if the user is using a screen reading device). If provided, it must be a non-empty string appropriate as a label for the button.

For example, if you have a graphical button that shows an image with an icon and/or image text «Login Now», you should also set the alt attribute to something like Login Now .

Note: While the alt attribute is technically optional, you should always include one to maximize the usability of your content.

Functionally, the alt attribute of the <input type=»image»> element works just like the alt attribute on <img> elements.

formaction

A string indicating the URL to which to submit the data. This takes precedence over the action attribute on the <form> element that owns the <input> .

This attribute is also available on <input type=»submit»> and <button> elements.

formenctype

A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:

This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as encodeURI() .

Uses the FormData API to manage the data, allowing for files to be submitted to the server. You must use this encoding type if your form includes any <input> elements of type file ( <input type=»file»> ).

Plain text; mostly useful only for debugging, so you can easily see the data that’s to be submitted.

If specified, the value of the formenctype attribute overrides the owning form’s action attribute.

This attribute is also available on <input type=»submit»> and <button> elements.

formmethod

A string indicating the HTTP method to use when submitting the form’s data; this value overrides any method attribute given on the owning form. Permitted values are:

A URL is constructed by starting with the URL given by the formaction or action attribute, appending a question mark («?») character, then appending the form’s data, encoded as described by formenctype or the form’s enctype attribute. This URL is then sent to the server using an HTTP get request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value.

The form’s data is included in the body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post request. This method supports complex data and file attachments.

This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all.

This attribute is also available on <input type=»submit»> and <button> elements.

formnovalidate

A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the novalidate attribute on the element’s owning form.

This attribute is also available on <input type=»submit»> and <button> elements.

formtarget

A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a browsing context (that is, a tab, window, or <iframe> . A value specified here overrides any target given by the target attribute on the <form> that owns this input.

In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used:

Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified.

Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.

Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as _self .

Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self .

This attribute is also available on <input type=»submit»> and <button> elements.

height

A number specifying the height, in CSS pixels, at which to draw the image specified by the src attribute.

A string specifying the URL of the image file to display to represent the graphical submit button. When the user interacts with the image, the input is handled like any other button input.

width

A number indicating the width at which to draw the image, in CSS pixels.

Obsolete attributes

The following attribute was defined by HTML 4 for image inputs, but was not implemented by all browsers and has since been deprecated.

usemap

If usemap is specified, it must be the name of an image map element, <map> , that defines an image map to use with the image. This usage is obsolete; you should switch to using the <img> element when you want to use image maps.

Using image inputs

The <input type=»image»> element is a replaced element (an element whose content isn’t generated or directly managed by the CSS layer), behaving in much the same way as a regular <img> element, but with the capabilities of a submit button.

Essential image input features

Let’s look at a basic example that includes all the essential features you’d need to use (These work exactly the same as they do on the <img> element.):

  • The src attribute is used to specify the path to the image you want to display in the button.
  • The alt attribute provides alt text for the image, so screen reader users can get a better idea of what the button is used for. It will also display if the image can’t be shown for any reason (for example if the path is misspelled). If possible, use text which matches the label you’d use if you were using a standard submit button.
  • The width and height attributes are used to specify the width and height the image should be shown at, in pixels. The button is the same size as the image; if you need the button’s hit area to be bigger than the image, you will need to use CSS (e.g. padding ). Also, if you specify only one dimension, the other is automatically adjusted so that the image maintains its original aspect ratio.

Overriding default form behaviors

<input type=»image»> elements — like regular submit buttons — can accept a number of attributes that override the default form behavior:

The URI of a program that processes the information submitted by the input element; overrides the action attribute of the element’s form owner.

Specifies the type of content that is used to submit the form to the server. Possible values are:

  • application/x-www-form-urlencoded : The default value if the attribute is not specified.
  • text/plain .

If this attribute is specified, it overrides the enctype attribute of the element’s form owner.

Specifies the HTTP method that the browser uses to submit the form. Possible values are:

  • post : The data from the form is included in the body of the form and is sent to the server.
  • get : The data from the form is appended to the form attribute URI, with a ‘?’ as a separator, and the resulting URI is sent to the server. Use this method when the form has no side effects and contains only ASCII characters.

If specified, this attribute overrides the method attribute of the element’s form owner.

A Boolean attribute specifying that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the element’s form owner.

A name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the element’s form owner. The following keywords have special meanings:

  • _ self : Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • _blank : Load the response into a new unnamed browsing context.
  • _parent : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self .
  • _top : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same as _self .

Using the x and y data points

When you submit a form using a button created with <input type=»image»> , two extra data points are submitted to the server automatically by the browser — x and y . You can see this in action in our X Y coordinates example.

When you click on the image to submit the form, you’ll see the data appended to the URL as parameters, for example ?x=52&y=55 . If the image input has a name attribute, then keep in mind that the specified name is prefixed on every attribute, so if the name is position , then the returned coordinates would be formatted in the URL as ?position.x=52&position.y=55 . This, of course, applies to all other attributes as well.

These are the X and Y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image and the default in case submission happens without a click on the image. These can be used when the position the image was clicked on is significant, for example you might have a map that when clicked, sends the coordinates that were clicked to the server. The server-side code then works out what location was clicked on, and returns information about places nearby.

In our above example, we could write server-side code that works out what color was clicked on by the coordinates submitted, and keeps a tally of the favorite colors people voted for.

Adjusting the image’s position and scaling algorithm

You can use the object-position property to adjust the positioning of the image within the <input> element’s frame, and the object-fit property to control how the image’s size is adjusted to fit within the frame. This allows you to specify a frame for the image using the width and height attributes to set aside space in the layout, then adjust where within that space the image is located and how (or if) it is scaled to occupy that space.

Examples

A login form

The following example shows the same button as before, but included in the context of a typical login form.

And now some simple CSS to make the basic elements sit more neatly:

Adjusting the image position and scaling

In this example, we adapt the previous example to set aside more space for the image and then adjust the actual image’s size and positioning using object-fit and object-position .

Here, object-position is configured to draw the image in the top-right corner of the element, while object-fit is set to contain , which indicates that the image should be drawn at the largest size that will fit within the element’s box without altering its aspect ratio. Note the visible grey background of the element still visible in the area not covered by the image.

<input type=»image»>

<input> Элементы <input> типа image используются для создания графических кнопок отправки, то есть кнопок отправки, которые принимают форму изображения, а не текста.

Try it

Value

<input type=»image»> Элементы <input type = «image»> не принимают атрибуты value . Путь к отображаемому изображению указывается в атрибуте src .

Additional attributes

В дополнение к атрибутам, общим для всех элементов <input> , входные данные кнопок image поддерживают следующие атрибуты.

alt атрибут обеспечивает альтернативные строки для использования в качестве метки для кнопки, если изображение не может быть показана (из — за ошибки, а агент пользователя , который не может или сконфигурирован , чтобы не показывать изображения, или если пользователь использует экран устройство чтения). Если указано, это должна быть непустая строка, подходящая в качестве метки для кнопки.

Например, если у вас есть графическая кнопка, которая показывает изображение со значком и / или текстом изображения «Войти сейчас», вы также должны установить для атрибута alt что-то вроде « Login Now .

Примечание. Хотя атрибут alt технически необязателен, вы всегда должны включать его, чтобы максимально повысить удобство использования вашего контента.

Функционально атрибут alt <input type=»image»> работает так же, как атрибут alt для элементов <img> .

formaction

Строка, указывающая URL-адрес для отправки данных. Это имеет приоритет над атрибутом action в элементе <form> , которому принадлежит <input> .

Этот атрибут также доступен для элементов <input type=»submit»> и <button> .

formenctype

Строка,определяющая метод кодирования при отправке данных формы на сервер.Существует три допустимых значения:

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

Использует FormData API для управления данными, что позволяет отправлять файлы на сервер. Вы должны использовать этот тип кодировки, если ваша форма включает какие -либо элементы <input> type file ( <input type=»file»> ).

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

Если указано, значение formenctype атрибута переопределяет форму , владеющей в action атрибут.

Этот атрибут также доступен для элементов <input type=»submit»> и <button> .

formmethod

Строка, указывающая метод HTTP для использования при отправке данных формы; это значение переопределяет любой атрибут method указанный в форме-владельце. Допустимые значения:

URL-адрес создается, начиная с URL-адреса, заданного formaction или action , добавляя знак вопроса («?»), А затем добавляя данные формы, закодированные, как описано с помощью formenctype или атрибута enctype формы . Затем этот URL-адрес отправляется на сервер с помощью HTTP- запроса на get . Этот метод хорошо работает для простых форм, содержащих только символы ASCII и не имеющих побочных эффектов. Это значение по умолчанию.

Данные формы включаются в тело запроса, который отправляется по URL-адресу, указанному в formaction или action , с помощью HTTP- запроса post . Этот метод поддерживает сложные данные и вложения файлов.

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

Этот атрибут также доступен для элементов <input type=»submit»> и <button> .

formnovalidate

Логический атрибут, который, если он присутствует, указывает, что форма не должна проверяться перед отправкой на сервер. Это отменяет значение атрибута novalidate в форме владельца элемента.

Этот атрибут также доступен для элементов <input type=»submit»> и <button> .

formtarget

Строка, указывающая имя или ключевое слово, указывающее, где отображать ответ, полученный после отправки формы. Строка должна быть именем контекста просмотра (то есть вкладки, окна или <iframe> . Указанное здесь значение переопределяет любую цель, заданную target атрибутом в <form> , которая владеет этим вводом.

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

Загружает ответ в тот же контекст просмотра,что и тот,который содержит форму.Это заменит текущий документ полученными данными.Это значение используется по умолчанию,если не указано ни одного.

Загружает ответ в новый безымянный контекст просмотра. Обычно это новая вкладка в том же окне, что и текущий документ, но она может отличаться в зависимости от конфигурации пользовательского агента .

Загружает ответ в родительский контекст просмотра текущего. Если родительский контекст отсутствует, он ведет себя так же, как _self .

Загружает ответ в контекст просмотра верхнего уровня; это контекст просмотра, который является самым верхним предком текущего контекста. Если текущий контекст является самым верхним контекстом, он ведет себя так же, как _self .

Этот атрибут также доступен для элементов <input type=»submit»> и <button> .

height

Число, указывающее высоту в пикселях CSS, на которой нужно нарисовать изображение, указанное атрибутом src .

Строка,указывающая URL файла изображения для отображения графической кнопки отправки.Когда пользователь взаимодействует с изображением,ввод обрабатывается как любая другая кнопка.

width

Цифра,указывающая ширину,на которой нужно нарисовать изображение,в пикселях CSS.

Obsolete attributes

Следующий атрибут был определен HTML 4 для входных данных image , но не был реализован всеми браузерами и с тех пор объявлен устаревшим.

usemap

Если usemap , это должно быть имя элемента карты изображения, <map> , который определяет карту изображения для использования с изображением. Это использование устарело; вам следует переключиться на использование элемента <img> , если вы хотите использовать карты изображений.

Использование графических входов

Элемент <input type=»image»> представляет собой заменяемый элемент (элемент, содержимое которого не создается или не управляется напрямую слоем CSS), который ведет себя так же, как обычный элемент <img> , но с возможностями из кнопки отправки .

Существенные особенности ввода изображения

Давайте рассмотрим базовый пример, который включает все основные функции, которые вам могут понадобиться (они работают точно так же, как и для элемента <img> .):

  • Атрибут src используется для указания пути к изображению, которое вы хотите отобразить на кнопке.
  • Атрибут alt предоставляет замещающий текст для изображения, поэтому пользователи программ чтения с экрана могут лучше понять, для чего используется кнопка. Он также будет отображаться, если изображение не может быть показано по какой-либо причине (например, если путь указан с ошибкой). Если возможно, используйте текст, который соответствует метке, которую вы использовали бы, если бы использовали стандартную кнопку отправки.
  • Атрибуты width и height используются для указания ширины и высоты изображения в пикселях. Кнопка имеет тот же размер, что и изображение; если вам нужно, чтобы область нажатия кнопки была больше, чем изображение, вам нужно будет использовать CSS (например, padding ). Кроме того, если вы укажете только одно измерение, другое будет автоматически настроено так, чтобы изображение сохраняло исходное соотношение сторон.

Преобладающее поведение формы по умолчанию

<input type=»image»> — как и обычные кнопки отправки — могут принимать ряд атрибутов, которые переопределяют поведение формы по умолчанию:

URI программы, которая обрабатывает информацию, предоставленную элементом ввода; переопределяет атрибут action владельца формы элемента.

Указывает тип контента,который используется для отправки формы на сервер.Возможные значения:

  • application/x-www-form-urlencoded : значение по умолчанию, если атрибут не указан.
  • text/plain .

Если этот атрибут указан, он переопределяет атрибут enctype владельца формы элемента.

Указание HTTP-метода,используемого браузером для отправки формы.Возможные значения:

  • post : данные из формы включаются в тело формы и отправляются на сервер.
  • get : данные из формы добавляются к URI атрибута form с помощью символа ‘?’ в качестве разделителя, и полученный URI отправляется на сервер. Используйте этот метод, если форма не имеет побочных эффектов и содержит только символы ASCII.

Если указан, этот атрибут переопределяет атрибут method владельца формы элемента.

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

Имя или ключевое слово, указывающее, где отображать ответ, полученный после отправки формы. Это имя или ключевое слово для контекста просмотра (например, вкладки, окна или встроенного фрейма). Если этот атрибут указан, он переопределяет target атрибут владельца формы элемента. Следующие ключевые слова имеют особое значение:

  • _ self : загрузить ответ в тот же контекст просмотра, что и текущий. Это значение используется по умолчанию, если атрибут не указан.
  • _blank : загрузить ответ в новый безымянный контекст просмотра.
  • _parent : загрузить ответ в родительский контекст просмотра текущего. Если родителя нет, этот параметр действует так же, как _self .
  • _top : загрузить ответ в контекст просмотра верхнего уровня (то есть контекст просмотра, который является предком текущего и не имеет родителя). Если родителя нет, этот параметр ведет себя так же, как _self .

Используя точки данных x и y

Когда вы отправляете форму с помощью кнопки, созданной с помощью <input type=»image»> , браузер автоматически отправляет на сервер две дополнительные точки данных — x и y . Вы можете увидеть это в действии в нашем примере с координатами XY .

Когда вы нажмете на изображение, чтобы отправить форму, вы увидите данные, добавленные к URL-адресу в качестве параметров, например, ?x=52&y=55 . Если входное изображение имеет атрибут name , то имейте в виду, что указанное имя имеет префикс для каждого атрибута, поэтому, если name — position , то возвращаемые координаты будут отформатированы в URL как ?position.x=52&position.y=55 . Это, конечно, относится и ко всем другим атрибутам.

Это координаты X и Y изображения,на которое щелкнула мышь,чтобы отправить форму,где (0,0)-левая верхняя часть изображения.Они могут быть использованы,когда положение изображения,на которое было нажато,является значительным,например,у вас может быть карта,которая при нажатии отправляет координаты,которые были нажаты на сервере.Код на стороне сервера затем выясняет,какое место было нажато,и возвращает информацию о местах поблизости.

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

Как сделать input картинкой

Чтобы сделать input картинкой (например, если у Вас кнопка формы создана тегом <input>, а не <button>) нужно использовать CSS. Пример:

Скопируй: style=»background-image: url(image.png);».

Здесь в input вставлена строка style=»background-image: url(image.png);». Через background-image и добавляется картинка. После url в скобках нужно указать путь до Вашей картинки.

Чтобы картинка не повторялась смотрите «Как сделать чтобы картинка не повторялась».
Чтобы задать размер картинки смотрите «Как изменить размер картинки».
Чтобы задать позицию изображения смотрите «Background-position в CSS — что это».

Добавить комментарий Отменить ответ

Privacy Overview

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

Cookie Duration Description
cookielawinfo-checkbox-analytics 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Analytics».
cookielawinfo-checkbox-functional 11 months The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category «Functional».
cookielawinfo-checkbox-necessary 11 months This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category «Necessary».
cookielawinfo-checkbox-others 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Other.
cookielawinfo-checkbox-performance 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Performance».
viewed_cookie_policy 11 months The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

Simple assigning an image to input type submit using CSS

Vivek Arora

Forms are an important part of the web design and development and are very commonly used. The most frequent use of form is when they are submitted using the action and method parameters. In that case we need an input type submit that will help to submit the form.

Sometimes the web design requirement is that the input type submit is assigned an image instead of it looking as a default html button which is not pretty. In those cases the following CSS can be used. I am going to write a simple HTML to show you how it works.

HTML

CSS
The CSS is very simple.

The above CSS assigns a background image to input type submit. It makes sure it doesnt repeat and sets the position to left most corner. You just have to make sure you give the width and height to be exactly equal to image. That’s it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *