窗口加载时浏览器缩放检测提示元素未插入body问题求助
修复方案
问题根因
- 初始校验代码执行时DOM还未加载完成,向body插入提示条的操作不生效,所以页面加载后不会自动弹出提示
- 还存在其他潜在问题:数字和字符串混用的比较错误、resize时会重复插入多条提示条、CSS属性语法错误、关闭按钮绑定的方法未定义
修复后代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CSS
#informationbar { position: fixed; left: 0; width: 100%; text-indent: 5px; padding: 5px 0; background-color: lightyellow; border-bottom: 1px solid black; font: bold 12px Verdana; } * html #informationbar { /*IE6 hack*/ position: absolute; width: expression(document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth + "px": body.clientWidth + "px"); }
JavaScript
function informationbar(percentage, zoomstatus) { // 先判断是否已存在提示条,避免重复插入 if ($('#informationbar').length) return $("body").append('<div id="informationbar" style="top: 0px;"><a href="javascript:informationbar.close()"><img src="#" style="width: 14px; height: 14px; float: right; border: 0; margin-right: 5px" /></a>You are using the window screen on ' + percentage + '% ' + zoomstatus + ' resolution, might some options are not visible properly on this current resolution please fit the screen on 100% as this our highly recommendation.</div>'); } // 补充关闭方法 informationbar.close = function() { $("#informationbar").remove() } // 把校验逻辑抽成公共方法,避免重复写 function checkZoomLevel() { var browserZoomLevel = Math.round(window.devicePixelRatio * 100); // 统一用数字比较,避免类型错误 if (browserZoomLevel === 100) { $("div#informationbar").remove(); return } var status = browserZoomLevel > 100 ? "ZoomIn" : "ZoomOut" informationbar(browserZoomLevel, status); } // 等DOM加载完成后再执行首次校验 $(function() { checkZoomLevel() }) $(window).resize(function() { checkZoomLevel() });
改动点说明
- 将校验逻辑抽为公共方法
checkZoomLevel,避免重复编码 - 首次校验放在jQuery的DOM就绪回调中执行,确保body元素存在时才操作DOM
- 统一用数字类型做比较,消除类型混用导致的判断异常
- 插入提示前先判断是否已存在,避免resize时重复插入多条提示
- 补充缺失的
informationbar.close方法,修复关闭按钮点击报错问题 - 修复CSS中属性名、属性值多打空格的语法错误
内容的提问来源于stack exchange,提问作者Sidharth
相关产品推荐
相关产品推荐

