我有一些基于浏览器窗口宽度隐藏div的代码。它在浏览器窗口中运行良好。当我尝试在推特iOS应用程序中打开同一页面时,代码不再有效。这是代码。
$(function () {
var isAdded = false;
$(window).resize(function () {
if ($(window).width() > 975) {
isAdded = true;
$('.sideBar').removeClass('hidden');
} else if ($(window).width() < 975) {
isAdded = false;
$('.sideBar').addClass('hidden');
}
});
});
如果我将alert(screen.width);
添加到第二个条件,则警报窗口不会显示在移动设备中。任何帮助表示赞赏
更新 我接受了Sphinxxx的回复并试了一下。它有效,但似乎有点草率。你们都觉得怎么样?我和js / jquery有点绿色
$(function () {
var isAdded = false;
$(window).load(function () {
if ($(window).width() < 975) {
isAdded = false;
$('.sideBar').addClass('hidden');
};
$(window).resize(function () {
if ($(window).width() > 975) {
isAdded = true;
$('.sideBar').removeClass('hidden');
} else if ($(window).width() < 975) {
isAdded = false;
$('.sideBar').addClass('hidden');
}
});
});
});
答案 0 :(得分:1)
您是否在meta
使用了<head>
?
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<强> UPD:强>
尝试用.ready()
函数替换包装函数:
$(document).ready(function() {
var isAdded = false;
$(window).resize(function () {
if ($(window).width() > 975) {
isAdded = true;
$('.sideBar').removeClass('hidden');
} else if ($(window).width() < 975) {
isAdded = false;
$('.sideBar').addClass('hidden');
}
});
$(window).resize(); // don't forget to trigger a code
});
答案 1 :(得分:0)
一种相当干净的方法是将调整代码放在一个单独的函数中,然后让load
和resize
调用该函数:
$(function () {
var win = $(window),
side = $('.sideBar'),
isAdded = false;
function rearrange() {
if (win.width() > 975) {
isAdded = true;
side.removeClass('hidden');
} else {
isAdded = false;
side.addClass('hidden');
}
}
win.load(rearrange);
win.resize(rearrange);
});