iOS 11 Safari bootstrap 光标外的模态文本区域

iOS 11 Safari bootstrap modal text area outside of cursor

使用iOS 11 safari,输入文本框光标在输入文本框之外。我们不明白为什么会出现这个问题。如您所见,我的焦点文本框是电子邮件文本输入,但我的光标在它外面。这只发生在 iOS 11 Safari

我通过在打开模式时向主体添加 position:fixed 解决了这个问题。 希望对您有所帮助。

打开模式时将 position: fixed; 添加到 body

$(document).ready(function($){
    $("#myBtn").click(function(){
        $("#myModal").modal("show");
    });
    $("#myModal").on('show.bs.modal', function () {
        $('body').addClass('body-fixed');
    });
    $("#myModal").on('hide.bs.modal', function () {
        $('body').removeClass('body-fixed');
    });
});
.body-fixed {
    position: fixed;
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Form</h4>
   </div>
   <div class="modal-body">
    <div class="form-group">
     <label class="control-label">Input #1</label>
     <input type="text" class="form-control">
    </div>
    <div class="form-group">
     <label class="control-label">Input #2</label>
     <input type="text" class="form-control">
    </div>
    <div class="form-group">
     <label class="control-label">Input #3</label>
     <input type="text" class="form-control">
    </div>
    <div class="form-group">
     <label class="control-label">Input #4</label>
     <input type="text" class="form-control">
    </div>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

令人沮丧的错误,感谢您识别它。否则,我会把我的 iphone 或我的头撞到墙上。

最简单的修复方法是(更改 1 行代码):

只需将以下 CSS 添加到 html 或外部 css 文件。

<style type="text/css">
.modal-open { position: fixed; }
</style>

这是一个完整的工作示例:

.modal-open { position: fixed; }
<link href="https://getbootstrap.com/docs/3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Open modal for @getbootstrap</button>
...more buttons...

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">New message</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="recipient-name" class="control-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="form-group">
            <label for="message-text" class="control-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://getbootstrap.com/docs/3.3/dist/js/bootstrap.min.js"></script>

我在这里提交了一个问题: https://github.com/twbs/bootstrap/issues/24059

这个问题超出了 Bootstrap,而且不仅仅是 Safari。这是iOS11中所有浏览器都会出现的全屏显示bug。上述修复并未在所有情况下解决此问题。

此处详细报告了错误:

https://medium.com/@eirik.luka/how-to-fix-the-ios-11-input-element-in-fixed-modals-bug-aaf66c7ba3f8

据说他们已经将其作为错误报告给 Apple。

你试过 viewport-fit=cover 元视口吗?

看看这个:https://ayogo.com/blog/ios11-viewport/

Easiest/cleanest 解决方案:

body.modal-open { position: fixed; width: 100%; }

就个人而言,position: fixed 自动滚动到顶部。很烦人!

为避免惩罚其他设备和版本,我仅将此修复程序应用于 iOS.

的适当版本

**版本 1 - 所有模态修复**

为javascript/jQuery

$(document).ready(function() {

    // Detect ios 11_x_x affected  
    // NEED TO BE UPDATED if new versions are affected
    var ua = navigator.userAgent,
    iOS = /iPad|iPhone|iPod/.test(ua),
    iOS11 = /OS 11_0|OS 11_1|OS 11_2/.test(ua);

    // ios 11 bug caret position
    if ( iOS && iOS11 ) {

        // Add CSS class to body
        $("body").addClass("iosBugFixCaret");

    }

});

为CSS

/* Apply CSS to iOS affected versions only */
body.iosBugFixCaret.modal-open { position: fixed; width: 100%; }

**版本 2 - 仅限选定的模态**

我将函数修改为仅针对具有 class .inputModal

的选定模态触发

只有带有输入的模式会受到影响,以避免滚动到顶部。

为javascript/jQuery

$(document).ready(function() {

    // Detect ios 11_x_x affected
    // NEED TO BE UPDATED if new versions are affected 
    (function iOS_CaretBug() {

        var ua = navigator.userAgent,
        scrollTopPosition,
        iOS = /iPad|iPhone|iPod/.test(ua),
        iOS11 = /OS 11_0|OS 11_1|OS 11_2/.test(ua);

        // ios 11 bug caret position
        if ( iOS && iOS11 ) {

            $(document.body).on('show.bs.modal', function(e) {
                if ( $(e.target).hasClass('inputModal') ) {
                    // Get scroll position before moving top
                    scrollTopPosition = $(document).scrollTop();

                    // Add CSS to body "position: fixed"
                    $("body").addClass("iosBugFixCaret");
                }
            });

            $(document.body).on('hide.bs.modal', function(e) {
                if ( $(e.target).hasClass('inputModal') ) {         
                    // Remove CSS to body "position: fixed"
                    $("body").removeClass("iosBugFixCaret");

                    //Go back to initial position in document
                    $(document).scrollTop(scrollTopPosition);
                }
            });

        }
    })();
});

为CSS

/* Apply CSS to iOS affected versions only */
body.iosBugFixCaret.modal-open { position: fixed; width: 100%; }

为HTML 添加 class inputModal 到 modal

<div class="modal fade inputModal" tabindex="-1" role="dialog">
    ...
</div>

注意事项 javascript 函数现在是自调用的


**更新iOS 11.3 - 修正了错误**

从 iOS 11.3 开始,错误已得到纠正。不需要在 iOS11 = /OS 11_0|OS 11_1|OS 11_2/.test(ua);

中测试 OS 11_

但要小心,因为 iOS 11.2 仍在广泛使用(截至 2018 年 4 月)。参见

stat 1

stat 2

覆盖模式 css 并将其 positionfixed 更改为 absolute

.modal {
position: absolute !important;
}

添加到#modal position:absolute 它修复了与位置相关的未来问题:已修复

如果有人正在寻找适用于 IOS >11.2 且不需要任何额外 CSS:

的 vanilla js 修复程序
(function() {
    if (!/(iPhone|iPad|iPod).*(OS 11_[0-2]_[0-5])/.test(navigator.userAgent)) return

    document.addEventListener('focusin', function(e) {
        if (!e.target.tagName == 'INPUT' && !e.target.tagName != 'TEXTAREA') return
        var container = getFixedContainer(e.target)
        if (!container) return
        var org_styles = {};
        ['position', 'top', 'height'].forEach(function(key) {
            org_styles[key] = container.style[key]
        })
        toAbsolute(container)
        e.target.addEventListener('blur', function(v) {
            restoreStyles(container, org_styles)
            v.target.removeEventListener(v.type, arguments.callee)
        })
    })

    function toAbsolute(modal) {
        var rect = modal.getBoundingClientRect()
        modal.style.position = 'absolute'
        modal.style.top = (document.body.scrollTop + rect.y) + 'px'
        modal.style.height = (rect.height) + 'px'
    }

    function restoreStyles(modal, styles) {
        for (var key in styles) {
            modal.style[key] = styles[key]
        }
    }

    function getFixedContainer(elem) {
        for (; elem && elem !== document; elem = elem.parentNode) {
            if (window.getComputedStyle(elem).getPropertyValue('position') === 'fixed') return elem
        }
        return null
    }
})()

这是做什么的:

  1. 检查浏览器是否为 iOS 11.0.0 - 11.2.5
  2. 上的 Safari
  3. 监听页面上的任何 focusin 事件
  4. 如果焦点元素是 inputtextarea 并且包含在具有 fixed 位置的元素中,将容器位置更改为 absolute 同时考虑 scrollTop 和容器的原始尺寸。
  5. 模糊时,将容器的位置恢复到 fixed

这个解决方案对我很有效,并且在 iOS 上的所有浏览器上运行良好。

.safari-nav-force{
/* Allows content to fill the viewport and go beyond the bottom */
height: 100%;
overflow-y: scroll;
/* To smooth any scrolling behavior */
-webkit-overflow-scrolling: touch;
}

JavaScript

var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
$('.modal').on('shown.bs.modal', function () {
    if (iOS && $('.modal').hasClass('in')){
        $('html,body').addClass('safari-nav-force');
    }
});
$('.modal').on('hidden.bs.modal', function () {
    if (iOS && !$('.modal').hasClass('in')){
        $('html,body').removeClass('safari-nav-force');
    }
});

如前所述:将bodystyle.position property设置为fixed解决了iOS cursor misplacement的问题。

然而,这种收获是以强制滚动到页面顶部为代价的。

幸运的是,这个新的 UX 问题可以通过利用 HTMLElement.style and window.scrollTo().

而无需太多开销就可以解决

基本要点是在 mounting 时通过操纵 body 元素的 style.top 来抵消 scroll to top。这是使用 ygap 变量捕获的 YOffset 值完成的。

从那里开始,只需将 body's style.top 重置为 0 并在 dismounting 时使用 window.scrollTo(0, ygap) 重新构建用户视图即可。

请参阅下面的实际示例。

// Global Variables (Manage Globally In Scope).
const body = document.querySelector('body') // Body.
let ygap = 0 // Y Offset.


// On Mount (Call When Mounting).
const onModalMount = () => {

  // Y Gap.
  ygap = window.pageYOffset || document.documentElement.scrollTop

  // Fix Body.
  body.style.position = 'fixed'

  // Apply Y Offset To Body Top.
  body.style.top = `${-ygap}px`

}


// On Dismount (Call When Dismounting).
const onModalDismount = () => {

  // Unfix Body.
  body.style.position = 'relative'

  // Reset Top Offset.
  body.style.top = '0'

  // Reset Scroll.
  window.scrollTo(0, ygap)

}

那些使用 position: fixed 和基于 scrollTop 的位置校正的解决方案非常有效,但有些人(包括我)遇到了另一个问题:键盘 caret/cursor 在输入聚焦时不显示.

我观察到 caret/cursor 仅在我们 不要 在 body 上使用 position: fixed 时才有效。所以在尝试了几件事之后,我放弃了使用这种方法并决定在 body 上使用 position: relative 并使用 scrollTop 来纠正 modal 的顶部位置 相反。

查看下面的代码:

var iosScrollPosition = 0;

function isIOS() {
   // use any implementation to return true if device is iOS
}

function initModalFixIOS() {
    if (isIOS()) {
        // Bootstrap's fade animation does not work with this approach
        // iOS users won't benefit from animation but everything else should work
        jQuery('#myModal').removeClass('fade');
    }
}

function onShowModalFixIOS() {
    if (isIOS()) {
        iosScrollPosition = jQuery(window).scrollTop();
        jQuery('body').css({
            'position': 'relative', // body is now relative
            'top': 0
        });
        jQuery('#myModal').css({
            'position': 'absolute', // modal is now absolute
            'height': '100%',
            'top': iosScrollPosition // modal position correction
        });
        jQuery('html, body').css('overflow', 'hidden'); // prevent page scroll
    }
}

function onHideModalFixIOS() {
    // Restore everything
    if (isIOS()) {
        jQuery('body').css({
            'position': '',
            'top': ''
        });
        jQuery('html, body').scrollTop(iosScrollPosition);
        jQuery('html, body').css('overflow', '');
    }
}

jQuery(document).ready(function() {
    initModalFixIOS();
    jQuery('#myModal')
        .on('show.bs.modal', onShowModalFixIOS)
        .on('hide.bs.modal', onHideModalFixIOS);
});

将您的 Apple 设备更新为 iOS11.3