Input css для iphone

CSS и iOS Safari

Доброго времени суток, дорогие хабрахабровцы!

Всегда хочется, что бы твой сайт выглядел одинаково хорошо на разных устройствах, включая и мобильные. Но, если поведение в браузерах Android во многом предсказуемо, то с iOS возникает ряд «сюрпризов». О них сегодня и поговорим!

Часть примеров уже публиковалась на Хабре, но я все-равно решил включить их в статью. Разделю статью на две части. В первой – приведу список полезных css-свойств для webkit, а во второй поговорим о фиксах проблем, возникающих при версте для iOS Safari.

Свойства

1. -webkit-overflow-scrolling: touch

Это css-свойство добавит плавный скролл в блоках с overflow: scroll. Рекомендую добавлять это свойство везде, где внутри блока может возникать прокрутка, к примеру, в мобильном меню.

2. -webkit-text-size-adjust: none

Отключает масштабирование текста в горизонтальной ориентации.

3. -webkit-tap-highlight-color: #ccc

Устанавливает цвет выделения активного элемента при тапе на нем (a, label). По умолчанию это серый цвет, и часто может быть ни к чему, или выбиваться из общего дизайна.

Пример такого выделения:

4. -webkit-appearance: none

Отключает наложение на элементы стилей системы: тени, border-radius и т.д. Применяется для input (но не всех), textarea, и т.д. Удобно, когда надо задать единый вид элементов на всех устройствах.

Применяется не только в верстке для Safari.

Данный медиа-запрос позволит отдельно прописывать стили только для устройств, с поддержкой тач. Таким образом, на тач-устройствах можно отключить лишние анимации, ненужные данным типам устройств.

Можно использовать не только в верстке для Safari.

Фиксы

1. background-attachment: fixed

Проблема: background-attachment: fixed не работает в iOS Safari.

Решение: Фиксировать не фон, а блок или псевдоэлемент.

2. Нежелательный скролл модального окна

Проблема: Это довольно редкий случай, но для общей информации, думаю, так же полезно будет знать о нем. Если модальное окно имеет собственную прокрутку и в закрытом состоянии просто установлен отрицательный z-index (и, к примеру, opacity: 0) — то при попытке скролла страницы, модальное окно может перехватить скролл. В результате чего не будет осуществляться прокрутка страницы.

Решение: Добавляем pointer-events: none к модальному окну в закрытом состоянии.

3. Пропадание меню при скролле
Для того, что бы меню «прилипало» к верхней границе экрана при скролле страницы, часто используют следующий прием. Изначально у меню установлено свойство position: absolute, и при достижении верхней границы окна, через js оно меняется на fixed. А при скролле страницы к началу, значение опять меняется на absolute.

Проблема: В Safari на iOS, при смене position с fixed на absolute, меню пропадает с экрана пока скролл не завершится.

Решение: Использовать для меню position: -webkit-sticky. Поведение меню будет сравнимо с вышеописанным, но пропадать ничего не будет! Плюс, не надо использовать js

К слову, значение sticky для свойства position сейчас поддерживается большим количеством браузеров, поэтому его можно использовать и в десктопных браузерах.

4. Блок с position: fixed при скролле

Если реализации решений предыдущих проблем я видел на некоторых сайтах, то данная проблема на сайтах встречается постоянно.

Читайте также:  Как выключить у айфона поворот экрана

Проблема: При скролле в браузере изменяется высота экрана. Отсюда, если при раскрытом меню или модальном окне не блокировать скролл, возникает подобный эффект:

Решение: Нужно сделать следующий «трюк», используя transform.

Величина в 70px покрывает разницу в изменении высоты окна. И только transform позволяет прорисовывать фон элемента за пределами экрана в данной ситуации.

Выводы

А выводов особо нет, просто пользуйтесь ) Если знаете еще полезные css-свойства или «фиксы», применимые на практике, пишите в комментариях!

Спасибо за внимание!

Update
В свойствах изменен пункт 5. Т.к. media (hover) имеет узкую поддержку. Спасибо dom1n1k за ценное замечание.

Источник

Remove iOS input shadow

On iOS (Safari 5) I have to following for input element (top inner shadow):

I want to remove top shadow, bug -webkit-appearance doesn’t save.

Current style is:

6 Answers 6

You’ll need to use -webkit-appearance: none; to override the default IOS styles. However, selecting just the input tag in CSS will not override the default IOS styles, because IOS adds it’s styles by using an attribute selector input[type=text] . Therefore your CSS will need to use an attribute selector to override the default IOS CSS styles that have been pre-set.

Try this:

Helpful Links:

You can learn more about appearance here:

If you’d like to learn more about CSS attribute selectors, you can find a very informative article here:

Seems to remove the shadows as well.

As @davidpauljunior mentioned; be careful setting -webkit-appearance on a general input selector.

webkit will remove all properties

Try using the property box-shadow to remove the shadow on your input element

Whilst the accepted answer is a good start, as others have pointed out, it only works for inputs whose type is «text» . There are a myriad of other input types which also render as text boxes on iOS, and so we need to expand this rule to take into account these other types.

Here’s the CSS I’m using to rid input text fields and textareas of the inner shadow, whilst preserving the default styling for buttons, checkboxes, range sliders, date/time dropdowns and radio buttons, all of which are authored using the humble tag too.

I tried to come up with a solution that a.) works and b.) I am able to understand why it works.

I do know that the shadow for inputs (and the rounded border for input[type=»search»]) comes from a background-image.

So obviously setting background-image: none was my first attempt, but this does not seem work.

Setting background-image: url() works, but i am still concerned about having a empty url() . Altough it currently is just a bad feeling.

background-clip: padding-box; seems to do the job as well, but even after reading the «background-clip» docs I don’t get why this completly removes the background.

My favorite solution:

This is valid css and I do understand how it works.

Источник

CSS input button on iPhone

I have this site here http://www.taranmarlowjewelry.com/?page_id=5 and in the top right corner I have an input button and it looks weird on an iphone and I don’t know why. It makes into a circle/bubble like button.

Heres the HTML for the input button

and here is the CSS

Any help would be gratefully appreciated!

3 Answers 3

I fixed my problem but adjusting my css like this.

By adding -webkit-appearance: none; the button now looks good an iphone, this also works for the iPad.

Читайте также:  Драйвер usb iphone для windows 7

If you have a lot of different buttons that this is an issue with on your site, try:

That should reset all of your input buttons without causing problems with checkboxes and other inputs. Just leave the rest of your CSS as-is.

consider setting -moz-appearance and -ms-appearance to none as well.

If you have access to a mac you can turn on developer tools in Safari and put the browser into iPhone simulation mode and try to debug it that way.

Not the answer you’re looking for? Browse other questions tagged iphone css or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.9.40958

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Создание кнопки переключения в стиле iOS с помощью CSS3 и Jquery

Как я уже говорил ранее, революция мобильных устройств началась, и теперь настало время создавать мобильные веб-приложения для своих веб-проектов. Многие сторонние платформы, такие как Apache Cordova и Phonegap, предлагают решения, с помощью которых вы можете конвертировать ваше веб-приложение в нативное мобильное приложение.

В этой статье я расскажу, как разработать кнопку переключения в стиле iOS с использованием HTML , CSS и Jquery . Особенно мне нравится использование псевдо-элементов CSS :before и :after . Это позволяет сократить HTML -код:

Примечание: для получения оптимального результата используйте браузеры Chrome , Firefox или Safari .

HTML код

Код HTML простой: нам всего лишь нужно включить элементы checkbox и switch DIV в тег label :

Switch контейнер

Простой HTML код:

После применения свойства border-radius :

Использование стиля Switch Before

:before является псевдо-элементом, вставляет стиль/контент перед DOM элементом:

Использование стиля Switch After

:after также является псевдо-элементом, вставляет стиль/контент после DOM элемента. В данном примере установка продолжительности перехода усиливает эффект анимации:

Стили SwitchOn :after :before

Задаем зеленый цвет для фона и перемещение:

Jquery код

Содержит код JavaScript , где в $(‘.switch’).click(function()<> — switch является именем класса для DIV . Используя Jquery класс toggleClass , можно добавлять и удалять класс switchOn , реагируя на клики мыши:

Финальная версия CSS

Элемент checkbox можно скрыть, задав display:none :

Источник

Better Password Inputs, iPhone Style

Take your JavaScript to the next level at Frontend Masters.

Recently renowned usability expert Jakob Nielsen wrote an article Stop Password Masking in which he claims that hiding users passwords as they input them is bad practice. What he is referring to is the default browser behavior of elements, where text entered into them turns into bullets rather than showing the real characters typed. He says it reduces user confidence in what they type and thus beginning a string of problems like more typing errors, users choosing overly-simple passwords or copying and pasting complex ones (less secure). The effect is ultimately less user satisfaction and ponentially less profit for you.

Of course he is right about all that, but masking passwords isn’t something that was developed and made default just for shits and giggles. It is to keep prying eyes away from looking at your screen and learning your passwords. This fact isn’t lost on Jakob who suggests making it a checkbox-style option.

Читайте также:  Может ли взорваться айфон при зарядке

Admittedly, someone peeking at your screen to capture a password is pretty rare. I’m alone in my office right now, like I am most of the time, and I bet that plant in the corner doesn’t have any secret cameras in it. I’m sure a lot of you are in similar environments. But I’m of the opinion that leaving important security up to users is typically not a good choice. Gruber linked to Jakob’s article, noting that the iPhone has an interesting solution to this already in use.

How the iPhone handles password inputs

  • The iPhone inputs turns text into bullet points like web password inputs, but after a quick delay, allowing you to see the typed character for a brief time.
  • The iPhone keyboard has a popup as you press each character verifying visually what character you just typed.

This is a pretty damn nice way to handle password inputs, which can be translated into use on the web. This handling of password inputs is a combination between giving better user feedback on key presses, increasing user confidence, yet still mostly hiding the password making it more difficult for casual onlookers.

We can replicate the idea behind both of these things, using jQuery!

Displaying pressed keys

Here is some super simple form markup with a password input:

We’ll use that internal div to set some relative positioning, and then set up some styling for a special div that we will insert on-the-fly in there for displaying the pressed key.

Then with jQuery, we can append that div and attach a keypress event to the input. When a key is pressed, that div will fade in with the letter, and fade back out. This will simulate the iPhones keyboard pressing letter verification.

Of course, you could style this up any way you want.

Changing text to bullets / only displaying last character

The next theory is making the text into bullets as you type them, but only after a short delay allowing you to see the typed character briefly. This is a bit more difficult. You could change the password input to be of type=”text”, but then changing the value to bullets would be problematic because of course you need to submit the real value of the field not bullets. You can’t leave the input as type=”password”, because nothing can be shown in those inputs except bullets.

The solution is to duplicate the password field, change it to a text input, and hide the original. This way you can use the new field and manipulate it however you want, but ultimately you submit the now-hidden password input which you keep up to date with current typed data.

We could set into writing this, but fortunately the DECAF o blog has already done the heavy lifting and created a jQuery plugin to do just this.

Simply target your password input and invoke the plugin:

Of course like any good plugin, there is a bunch of options you can pass as parameters like the delay before switching, the prefix for the duplicated input, and more.

What do you guys think? Is this a good middle ground or the worst of both worlds?

Источник

Оцените статью