rdo*_*720 53 javascript css iphone mobile jquery
我正在开发我的网站的移动版本.我尽可能地使用媒体查询和CSS,但我也使用一些javascript,例如,将我的导航转换为较小设备上的折叠/展开列表以节省空间.
为了处理所有这些,我试图使用window.resize事件.这样可以在桌面浏览器调整大小时实现魔力,但是当我不期待它们时,我会在iPad/iPhone上调整大小.
在桌面浏览器上,如果我实际调整窗口大小,我只会收到调整大小事件.在移动浏览器上,当我更改方向(预期)时,我会收到调整大小事件,但是当我切换到展开/折叠某些内容时,我也会得到它.
这是一个简单的例子:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<title>Resize test</title>
<style>
.box {height: 10000px; background: green; display: none;}
</style>
<script>
$(function(){
$(".opener").click(function(){
$(".box").slideToggle();
});
$(window).resize(function(){
alert("resized");
});
});
</script>
</head>
<body>
<a href="#" class="opener">Open/close me</a>
<div class="box"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
单击桌面浏览器上的链接时,不会发出警报.点击iPhone/iPad上的链接,即可获得提醒.这是怎么回事?
Jam*_*eig 115
在继续执行$(window).resize功能之前,存储窗口宽度并检查它是否已实际更改:
jQuery(document).ready(function($) {
// Store the window width
var windowWidth = $(window).width();
// Resize Event
$(window).resize(function(){
// Check window width has actually changed and it's not just iOS triggering a resize event on scroll
if ($(window).width() != windowWidth) {
// Update the window width for next time
windowWidth = $(window).width();
// Do stuff here
}
// Otherwise do nothing
});
});
Run Code Online (Sandbox Code Playgroud)
这是已接受答案的原始javascript版本
document.addEventListener('DOMContentLoaded', function() {
// Store the window width
var windowWidth = window.innerWidth
// Resize Event
window.addEventListener("resize", function() {
// Check window width has actually changed and it's not just iOS triggering a resize event on scroll
if (window.innerWidth != windowWidth) {
// Update the window width for next time
windowWidth = window.innerWidth
// Do stuff here
}
// Otherwise do nothing
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34813 次 |
| 最近记录: |