Bootstrap Vue模态框关闭时Safari浏览器页面异常跳转问题咨询
根因分析
该问题是Safari特有的焦点滚动计算兼容问题:Bootstrap Vue <b-modal> 默认启用return-focus特性,关闭模态框时会自动将焦点归还到触发模态框打开的按钮元素。Safari计算焦点元素的视口位置时,会忽略页面内fixed定位元素、动态布局变化带来的偏移,最终导致滚动位置跳转到错误的区域。
修复方案
不需要额外绑定preventDefault,仅需调整模态框配置即可修复:
- 优先方案:给
<b-modal>添加return-focus="false"属性,禁用默认的焦点回弹逻辑,直接解决Safari的异常滚动问题 - 如果你需要保留「关闭后回到触发按钮位置」的交互预期,可以手动记录滚动位置,关闭后主动定位,完全规避浏览器兼容问题
调整后完整代码
<template> <b-modal :visible="visible" size="lg" centered @hidden="closeModal" hide-footer return-focus="false" > <p>modal body</p> <template #default> <div class="w-100"> <b-button class="btn btn-icon" @click.prevent="closeModal" > <span class="l-btn float-left"> <span class="btn-text">Cancel</span> <i class="btn-icon-symbol"></i> </span> </b-button> <a :href="$store.state.modals.interstitial.href" target="_blank" class="btn btn-icon btn-icon-arrow" > <span class="l-btn float-left"> <span class="btn-text text-white">OK</span> <i class="btn-icon-symbol text-white"></i> </span> </a> </div> </template> </b-modal> </template> <script> import { BButton } from 'bootstrap-vue'; export default { name: 'Modal', components: { BButton }, computed: { visible() { return this.$store.state.modals.interstitial.show; } }, // 仅需要保留原滚动位置交互时添加以下watch和data逻辑 watch: { visible(isShow) { if (isShow) { this.openScrollTop = window.pageYOffset || document.documentElement.scrollTop; } else { window.scrollTo({ top: this.openScrollTop, behavior: 'auto' }); } } }, data() { return { openScrollTop: 0 }; }, methods: { closeModal() { this.$store.commit('modals/setShowModal', false); this.$store.commit('modals/setModalHref', ''); } } }; </script>
注:原代码中未标注插槽名称,补充了
#default具名插槽标识,避免部分版本Bootstrap Vue出现插槽内容不渲染的问题。
内容的提问来源于stack exchange,提问作者hendy0817
相关产品推荐
相关产品推荐

