Mozilla input type number убрать стрелки
Одно из таких значении : "type number" - тип числовой.
Longer answer:
To add to existing answer.
Chrome:
In current versions of Chrome, the (user agent) default value of the -webkit-appearance property on these elements is already textfield . In order to remove the spinner, the -webkit-appearance property's value needs to be changed to none on the ::-webkit-outer-spin-button / ::-webkit-inner-spin-button pseudo classes (it is -webkit-appearance: inner-spin-button by default).
It's worth pointing out that margin: 0 is used to remove the margin in older versions of Chrome.
Currently, as of writing this, here is the default user agent styling on the 'inner-spin-button' pseudo class:
i like this answer better because it includes relevant firefox info, which, when developing something, needs to be considered. webkit-only answers that ignore other browser engines leave much to be desired
According to Apple’s user experience coding guide for mobile Safari, you can use the following to display a numeric keyboard in the iPhone browser:
A pattern of \d* will also work.
This currently does nothing on Android, in all browsers. Tested on this test page in Browser 4.2.2, Chrome 28, and Firefox 23 on Android 4.2. Those browsers just show the standard text keyboard with this markup.
I found a super simple solution using
technology.blog.gov.uk/2020/02/24/… explains why UK gov switched from type="number" to this solution.
Try using input type="tel" instead. It pops up a keyboard with numbers, and it doesn’t show spin boxes. It requires no JavaScript or CSS or plugins or anything else.
The telephone keyboard is not as good as the number keyboard, though it’s far better than the text keyboard. The telephone keyboard has irrelevant letters and symbols that are omitted from the number keyboard. (Tested with this page on Android 4.2.)
This is not a solution, and by the HTML5 standards its stupid. input[tel] is for phone numbers, input[number] is for generic numbers, including floating point ones. So this is not a solution at all.
Only add this css to remove spinner on input of number
I've encountered this problem with a input[type="datetime-local"] , which is similar to this problem.
And I've found a way to overcome this kind of problems.
First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"
Then you can see all shadowed DOM elements, for example, for , the full element with shadowed DOM is:
And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.
Пример использования step - шаг в type number
Поставим значение step=2
Дополнительно добавим в поле выше перечисленные атрибуты ( min="0" max="10" )
On Firefox 28, I'm using works great because it brings up the numerical keyboard on input fields which should only contain numbers.
In Firefox 29, using number inputs displays spin buttons at the right side of the field, which looks like crap in my design. I really don't need the buttons, because they are useless when you need to write something like a 6~10 digit number anyway.
Is it possible to disable this with CSS or jQuery?
If you don't want the spin arrows, then don't use type="number" . You can use type="text" and the pattern attribute to set a regex to make sure it's a number.
-webkit-inner-spin-button -webkit-outer-spin-button with -webkit-appearance: none; margin: 0; Dont Work in Firefox.
@RocketHazmat: type="number" is required for mobile browsers to show the numeric keyboard instead of the full keyboard.
Убираем стрелки в "Microsoft Edge" тестовый скрин :
Убираем стрелки в ‘Microsoft Edge‘ тестовый скрин :
Синтаксис type number + "max"
Пример использования type number.
Мы не рассмотрели условие по которому будем получать данные в php :
Соберем весь код вместе:
Убираем стрелки в "Internet Explorer" тестовый скрин :
Результат -> убрали стрелки у типа числового type number:
Результат применения type number:
Другие публикации
CSS стили для атрибута placeholder можно задать через псевдокласс ::placeholder и вендорными префиксами для разных браузеров.
В Firefox 28 я использую отлично работает, потому что он вызывает цифровую клавиатуру в полях ввода, которые должны содержать только числа.
В Firefox 29 при использовании числового ввода кнопки вращения отображаются в правой части поля, что в моем дизайне выглядит как дерьмо. Мне действительно не нужны кнопки, потому что они бесполезны, когда вам все равно нужно написать что-то вроде числа из 6-10 цифр.
Можно ли отключить это с помощью CSS или jQuery?
Если вам не нужны стрелки вращения, не используйте type="number" . Вы можете использовать type="text" и pattern атрибут , чтобы установить регулярное выражение , чтобы убедиться , что это число.
-webkit-inner-spin-button -webkit-external-spin-button с -webkit-appearance: none; маржа: 0; Не работайте в Firefox.
@RocketHazmat: type="number" требуется, чтобы мобильные браузеры отображали цифровую клавиатуру вместо полной клавиатуры.
Менять type="text" - плохая идея, потому что сенсорные устройства показывают неправильную клавиатуру.
Я обернул это, @-moz-document url-prefix() < . >и он делает то, что я хочу: скрывает счетчики в Firefox, где они выглядят плохо, но сохраняет их живыми в других браузерах, включая те, которые вызывают цифровую клавиатуру, как упоминалось в OP.
@JovanniG: Даже если вы не удалите счетчики, вы все равно можете вводить нечисловые символы во ввод в Firefox. Попробуйте это с демонстрацией на MDN . Chrome предотвращает нечисловой ввод в обоих примерах.
@alxndr: Кроме того, я только что попробовал «Выполнить фрагмент кода» в Chrome 66, и он работает, как ожидалось.
Стоит отметить, что значение по умолчанию для -moz-appearance этих элементов установлено number-input в Firefox.
Если вы хотите скрыть счетчик по умолчанию, вы можете установить его -moz-appearance: textfield изначально, и если вы хотите, чтобы счетчик отображался на :hover / :focus , вы можете перезаписать предыдущий стиль с помощью -moz-appearance: number-input .
Я подумал, что кто-то может найти это полезным, так как мне недавно пришлось сделать это в попытках улучшить согласованность между Chrome / FF (поскольку именно так числовые вводы ведут себя по умолчанию в Chrome).
Если вы хотите увидеть все доступные значения для -moz-appearance , вы можете найти их здесь (mdn).
Firefox:
In current versions of Firefox, the (user agent) default value of the -moz-appearance property on these elements is number-input . Changing that to the value textfield effectively removes the spinner.
In some cases, you may want the spinner to be hidden initially, and then appear on hover/focus. (This is currently the default behavior in Chrome). If so, you can use the following:
Характеристики типа number :
Ти числовой - "type number" - применяется для ввода чисел в поле ввода. Модно ввести число набором с клавиатуры, либо нажав по стрелке в поле ввода Увеличить/уменьшить.
Убираем стрелки в "Яндекс браузере" тестовый скрин :
Убираем стрелки в ‘Яндекс браузере‘ тестовый скрин :
Установка максимального значения "max" в type number
Alternative solution
Instead, they recommend to use which comes down to the combined answers of @team_steve and @youjin. This not only hides the spin boxes, it also improves the overall usability of the element.
Can still type in non-numeric characters - which is undesired. The usability thing is not always important, as the limitation effect of allowing to input only numbers, which is a huge plus
You can put in non-numeric characters but not submit the form. I'd argue that's a plus because this way you can detect errors and give a proper validation message. If someone mistypes but only can put in numbers, the values might be right according to the rules but not from a user point of view. For example if someone types in 1K , they mean 1000 . But if the K can't be typed in, you cannot detect this mistake. The input will be 1 , which is not what was meant.
Ture, but consider form ancestor element is not a must, and it's more common for "form" components not to be wrapped with a
В HTML5 появилось специальное поле с атрибутом type="number" для вода чисел. Рассмотрим его возможности.
Для поля доступны следующие атрибуты:
Атрибут | Описание |
---|---|
step | Шаг изменения значения |
max | Максимальное значение |
min | Минимальное значение |
placeholder | Подсказка |
readonly | Только для чтения |
disabled | Заблокирован |
list | Связка со списком опций datalist по id |
required | Обязательный для заполнения |
Как стилизовать стрелки
К стрелкам не применить CSS стили, но есть JS-методы stepUp() и stepDown() для изменения значения. Так можно скрыть стрелки и добавить свои кнопки:
Результат:
Убрать стрелки
Установка минимального значения "min" в type number
Для типа type number существует дополнительный атрибут "min" - который устанавливает минимальное значение для type number .
Убираем стрелки в "Опере" тестовый скрин :
Убираем стрелки в ‘Опере‘ тестовый скрин :
20 Answers 20
This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):
You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":
It seems that Chrome no longer has a problem, so you can just use display: none; as the only thing inside the selector
This is unfortunately not cross-browser so I'd advise against using type=number if you have to hide these arrows. E.g. currently they'd be still displayed in Opera and they'll start being displayed in Firefox, IE etc. when they implement this input type.
Firefox 29 currently adds support for number elements, so here's a snippet for hiding the spinners in webkit and moz based browsers:
Стилизация
Стандартными CSS-стилями можно изменить инпут:
Пример:
Установка шага "step" в type number
Кроме выше приведенных двух атрибутов, дополнительно атрибут step :
Максимальное значение
Атрибут max="100" задает максимально возможное значение value .
Пример:
Пример использования минимального значения в type number
Поставим значение min=0
Вы можете потренироваться выбрать число менее минимального значения!
Синтаксис type number + "step"
Минимальное значение
Атрибут min="1" задает минимально возможное значение value . Это значение должно быть меньше или равно значению max . Может быть целым, отрицательным или дробным.
Пример:
Short answer:
Комментарии 1
Спасибо за очень полезный урок Мало где такое объяснение встретишь.Но я никак не могу решить, как реализовать ваше решение в Друпал 8.В шаблоне формы input.html.twig?Меня интересует пример №8 Стилизация кнопок.Как применить имеющийся у вас пример к существующему полю input number?Как например прописать этот код в теме сайта?
Синтаксис type number + "min"
Опции по умолчанию
У поля есть возможность задать список с рекомендуемыми значениями с помощью элемента .
Пример:
Шаг изменения
Атрибут step="1" задает на сколько будет увеличиваться или уменьшаться значение в поле. Может быть как целым (10) так и дробным (0.1).
Пример:
Input type number убрать стрелки
Мы не можем пройти момо такой популярной темы, как : "Input type number убрать стрелки"
Для того, чтобы избавиться от стрелок в type number, нужно применить кни соответствующие стили:
/* display: none; HTML :
type the numbers перевод на русский
type - с английского на русский : " ТИП "
the - не переводится - это артикль(определенный).
numbers - с английского на русский : " номер, число(сущ.), насчитывать, нумеровать(гл.) "
Синтаксис type number html.
Как использовать данный type number на сайте.
Кроме поле ввода :
И еще одно поле ввода с другим типом submit
Вам потребуется метод post.
Пример использования максимального значения в type number
Поставим значение max=10
Вы можете потренироваться выбрать число более максимального значения!
Валидация
Если указать атрибут required , то при отправки формы будет проверятся заполнено поле или нет, а также превышение введенного значения value в атрибутах min и max .
Проверить значение регулярным выражением с помощью атрибута pattern не получится, т.к. он не поддерживается.
Пример:
Также доступны CSS псевдо свойства :invalid и :valid , с помощью них можно применить стили к неправильно заполненному полю.
Пример:
Usability Issues
- cannot be dictated or selected when using Dragon Naturally Speaking
- appears as unlabeled in NVDA's element list
- appears as a spin button in NVDA's object navigation, which has an edit field and two buttons inside - those buttons are unlabeled, but decrease/increase the value
- is reported as unlabeled edit field when using nvda+tab
8 Answers 8
According to this blog post, you need to set -moz-appearance:textfield; on the input .
I wrapped this in @-moz-document url-prefix() < . >and it does what I want: hides the spinners in Firefox, where they look bad, but keep them alive in other browsers, including ones that bring up the numeric keyboard as the OP mentioned.
this works and indeed it removes the spinners, but then you are now able to enter alphanumeric characters into it. Hope somebody finds a way to handle that scenario without having to check the entered keys if they are numbers or not.
@JovanniG: Even if you don't remove the spinners, you can still enter non-numeric characters into the input in Firefox. Try it with the demo on MDN. Chrome prevents non-numeric input in both examples.
It's worth pointing out that the default value of -moz-appearance on these elements is number-input in Firefox.
If you want to hide the spinner by default, you can set -moz-appearance: textfield initially, and if you want the spinner to appear on :hover / :focus , you can overwrite the previous styling with -moz-appearance: number-input .
I thought someone might find that helpful since I recently had to do this in attempts to improve consistency between Chrome/FF (since this is the way number inputs behave by default in Chrome).
If you want to see all the available values for -moz-appearance , you can find them here (mdn).
Is there a consistent way across browsers to hide the new spin boxes that some browsers (such as Chrome) render for HTML input of type number? I am looking for a CSS or JavaScript method to prevent the up/down arrows from appearing.
Can you post an example of the code you're using? A screenshot would be great as well so we know what you're looking at. I'm looking at
in Chrome and seeing a typical input field with up and down arrows on the side.
You are seeing exactly what I am seeing. I am trying to keep the type=number markup to ensure that mobile browsers bring up an appropriate keyboard, and prevent the up and down arrows from appearing in computer browsers.
What I suggest doing is writing markup along the lines of and using jQuery Validati or similar to handle validation. I haven't tested this approach, which is why this is a comment, rather than an answer.
Убираем стрелки в "Google Chrome" тестовый скрин :
Убираем стрелки в ‘Google Chrome‘ тестовый скрин :
Читайте также: