我制作了一个HTML页面,其中有一个<input>标记,类型为“text”。当我在iPhone上使用Safari点击它时,页面会变大(自动缩放)。有人知道如何禁用此功能吗?
当前回答
这在iOS Safari和Chrome上对我有效。对于输入选择器,可以将类或id设置为包含当前值。
@supports (-webkit-overflow-scrolling: touch) {
input {
font-size: 16px;
}
}
其他回答
将字体大小(用于输入字段)设置为等于正文的字体大小,似乎是阻止浏览器缩小或缩小的原因。我建议使用字体大小:1rem作为更优雅的解决方案。
经过一段时间的尝试,我想出了这个解决方案
// set font-size to 16px to prevent zoom
input.addEventListener("mousedown", function (e) {
e.target.style.fontSize = "16px";
});
// change font-size back to its initial value so the design will not break
input.addEventListener("focus", function (e) {
e.target.style.fontSize = "";
});
在“mousedown”时,它将输入的字体大小设置为16px。这将阻止缩放。在焦点事件中,它将字体大小更改回初始值。
与之前发布的解决方案不同,这将允许您将输入的字体大小设置为任意大小。
这在iOS Safari和Chrome上对我有效。对于输入选择器,可以将类或id设置为包含当前值。
@supports (-webkit-overflow-scrolling: touch) {
input {
font-size: 16px;
}
}
使用(悬停:无)和(指针:粗略)以所有触摸屏设备为目标:
这里的许多答案都依赖于部署JavaScript或jQuery。
但它应该(而且是)完全可以用CSS控制条件字体表示等问题。
Safari Mobile要求(有充分的理由)与任何表单元素交互时,其最小字体大小必须为16px(或视觉等效值)。
让我们致力于让经过深思熟虑的用户体验应用于所有触摸屏浏览器。
然后我们可以采取以下措施:
@media only screen and (hover: none) and (pointer: coarse) {
input,
select,
textarea {
font-size: 11px;
}
input:focus,
select:focus,
textarea:focus {
font-size: 16px;
}
}
结果
当使用触摸屏设备时,当上面的任何交互式表单元素被聚焦时,该表单元素的字体大小被临时设置为16px。
这反过来会禁用iOS Safari Mobile自动缩放。
用户初始化的捏缩缩放在所有设备上都不受影响,并且永远不会被禁用。
正如许多其他答案已经指出的那样,这可以通过向元视口标记添加最大比例来实现。然而,这会导致在Android设备上禁用用户缩放功能。(自v10以来,它不会在iOS设备上禁用用户缩放。)
当设备为iOS时,我们可以使用JavaScript动态地向元视口添加最大比例。这实现了两全其美:我们允许用户缩放,并防止iOS缩放到聚焦的文本字段。
| maximum-scale | iOS: can zoom | iOS: no text field zoom | Android: can zoom |
| ------------------------- | ------------- | ----------------------- | ----------------- |
| yes | yes | yes | no |
| no | yes | no | yes |
| yes on iOS, no on Android | yes | yes | yes |
代码:
const addMaximumScaleToMetaViewport = () => {
const el = document.querySelector('meta[name=viewport]');
if (el !== null) {
let content = el.getAttribute('content');
let re = /maximum\-scale=[0-9\.]+/g;
if (re.test(content)) {
content = content.replace(re, 'maximum-scale=1.0');
} else {
content = [content, 'maximum-scale=1.0'].join(', ')
}
el.setAttribute('content', content);
}
};
const disableIosTextFieldZoom = addMaximumScaleToMetaViewport;
// https://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885#9039885
const checkIsIOS = () =>
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (checkIsIOS()) {
disableIosTextFieldZoom();
}