我发现当我在页面中监听基于宽度的 matchMedia 查询时,它会在我打印时调用。
这是一个更全面的片段:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no,viewport-fit=cover" />
</head>
<body>
<div>Open me in chrome, look at the console and print the page</div>
<script>
const mediaQuery = window.matchMedia('only screen and (min-width: 768px)')
mediaQuery.addEventListener('change', () => {
console.log('change width event', { innerWidth: window.innerWidth, outerWidth: window.outerWidth })
})
</script>
</body>
</html>
在我的控制台中,当我打印时,我可以看到 window.innerWidth
的值为 555,然后使用我的窗口的正确值(大于 555)立即调用 mediaQuery .
为什么会发生这种情况,我们该如何禁用它?
最佳答案
可能是因为only screen
与print
相反。
当您打印页面时,查询将不再适用,并且会调用 matchMedia 事件
只需删除 only screen
可能 解决您的问题
编辑:另一个想法可能是使用 window.onberforeprint
捕获打印请求(window.addEventListener("beforeprint", function(event) { ... });
) 并设置一个 bool 值,这样您现在就可以打印页面了
关于javascript - 为什么在 Chrome 中打印页面时会调用 window.matchMedia?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69241031/