如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
如果我的屏幕宽度小于960像素,我如何让jQuery做一些事情?下面的代码总是触发第二个警报,不管我的窗口大小:
if (screen.width < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
当前回答
你可能想把它和一个resize事件结合起来:
$(window).resize(function() {
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
});
R.J。:
var eventFired = 0;
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
eventFired = 1;
}
$(window).on('resize', function() {
if (!eventFired) {
if ($(window).width() < 960) {
alert('Less than 960 resize');
} else {
alert('More than 960 resize');
}
}
});
我尝试http://api.jquery.com/off/没有成功,所以我使用eventFired标志。
其他回答
使用jQuery获取窗口的宽度。
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
// Adds and removes body class depending on screen width.
function screenClass() {
if($(window).innerWidth() > 960) {
$('body').addClass('big-screen').removeClass('small-screen');
} else {
$('body').addClass('small-screen').removeClass('big-screen');
}
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
screenClass();
});
我知道现在回答这个问题有点晚了,但我希望这对有类似问题的人有所帮助。当页面因任何原因刷新时,它也可以工作。
$(document).ready(function(){
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
$(window).resize(function() {
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
else{
$("#up").show();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
else{
$("#up").show();
}
});});
试试这段代码
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
If ($(window).width() < 960) { 警报('宽度小于960px'); } 其他{ alert('大于960'); } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>
你可能想把它和一个resize事件结合起来:
$(window).resize(function() {
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
});
R.J。:
var eventFired = 0;
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
eventFired = 1;
}
$(window).on('resize', function() {
if (!eventFired) {
if ($(window).width() < 960) {
alert('Less than 960 resize');
} else {
alert('More than 960 resize');
}
}
});
我尝试http://api.jquery.com/off/没有成功,所以我使用eventFired标志。