简体   繁体   English

如果屏幕宽度小于 960 像素,请执行某些操作

[英]Do something if screen width is less than 960 px

How can I make jQuery do something if my screen width is less than 960 pixels?如果我的屏幕宽度小于 960 像素,我如何让 jQuery 执行某些操作? The code below always fires the 2nd alert, regardless of my window size:无论我的窗口大小如何,下面的代码总是会触发第二个警报:

if (screen.width < 960) {
    alert('Less than 960');
}
else {

    alert('More than 960');
}

Use jQuery to get the width of the window.使用 jQuery 获取窗口的宽度。

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

You might want to combine it with a resize event:您可能希望将其与调整大小事件结合使用:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

For RJ:对于 RJ:

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');
        }
    }
});

I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.我尝试了http://api.jquery.com/off/ 但没有成功,所以我使用了 eventFired 标志。

I recommend not to use jQuery for such thing and proceed with window.innerWidth :我建议不要将 jQuery 用于此类事情并继续使用window.innerWidth

if (window.innerWidth < 960) {
    doSomething();
}

You can also use a media query with javascript.您还可以使用带有 javascript 的媒体查询。

const mq = window.matchMedia( "(min-width: 960px)" );

if (mq.matches) {
       alert("window width >= 960px");
} else {
     alert("window width < 960px");
}
// 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();
});

I would suggest (jQuery needed) :我建议(需要jQuery):

/*
 * windowSize
 * call this function to get windowSize any time
 */
function windowSize() {
  windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
  windowWidth = window.innerWidth ? window.innerWidth : $(window).width();

}

//Init Function of init it wherever you like...
windowSize();

// For example, get window size on window resize
$(window).resize(function() {
  windowSize();
  console.log('width is :', windowWidth, 'Height is :', windowHeight);
  if (windowWidth < 768) {
    console.log('width is under 768px !');
  }
});

Added in CodePen : http://codepen.io/moabi/pen/QNRqpY?editors=0011在 CodePen 中添加: http ://codepen.io/moabi/pen/QNRqpY?editors=0011

Then you can get easily window's width with the var : windowWidth and Height with : windowHeight然后,您可以使用 var 轻松获得窗口的宽度:windowWidth 和 Height 使用:windowHeight

otherwise, get a js library : http://wicky.nillia.ms/enquire.js/否则,获取一个 js 库: http : //wicky.nillia.ms/enquire.js/

I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem.我知道我回答这个问题晚了,但我希望它对任何有类似问题的人有所帮助。 It also works when page refreshes for any reason.当页面因任何原因刷新时,它也有效。

$(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();
    }

});});

use

$(window).width()

or或者

$(document).width()

or或者

$('body').width()

Try this code试试这个代码

if ($(window).width() < 960) {
 alert('width is less than 960px');
}
else {
 alert('More than 960');
}

 if ($(window).width() < 960) { alert('width is less than 960px'); } else { alert('More than 960'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

My solution for the question using Vanilla JS is,我对使用 Vanilla JS 的问题的解决方案是,

window.addEventListener("load", function () {
  if (window.innerWidth < 960) { doSomething(); }
}

This works, but with one problem, whenever resizing the screen in dev tools, which is a common thing for developers, the function does something will not be fired.这可行,但有一个问题,每当在开发工具中调整屏幕大小时,这对开发人员来说是一件很常见的事情,function 所做的事情不会被解雇。

For example, if we display the webpage on a computer with a screen size of more than 1000px, the function will not be fired, and when we resize the windows to less than the target(here 960px) we expect the event to be fired but that is not what happens.例如,如果我们在屏幕大小超过 1000px 的计算机上显示网页,则不会触发 function,当我们将 windows 的大小调整为小于目标(此处为 960px)时,我们希望该事件被触发,但事实并非如此。

By the time the script file is already processed and finished and will not be re-read, so we need to fire an event whenever we resize the screen and handle that event using "addEventListener", Just like this;等到脚本文件已经处理完毕并且不会被重新读取时,我们需要在调整屏幕大小时触发一个事件并使用“addEventListener”处理该事件,就像这样;

window.addEventListener("resize", (e) => {
  const windowWidth = window.innerWidth;
  if (windowWidth > 960) { doSomething(); }
  if (windowWidth < 960) { doSomething(); }
});

The best practise is to combine both the code-snippets in the project.最佳实践是将项目中的两个代码片段结合起来。

Simple and clean solution using Vanilla JavaScript使用 Vanilla JavaScript 的简单干净的解决方案

 let app = document.getElementById('app') const changeColorFn = ( app, color ) => { app.setAttribute("style",`background: ${color}`) } const winSizeFn = ( winWidth, callback, app, color ) => { if (window.innerWidth < winWidth ) { callback(app, color); } } winSizeFn( '1200', changeColorFn, app, 'red' ) winSizeFn( '800', changeColorFn, app, 'green' ) winSizeFn( '500', changeColorFn, app, 'blue' ) window.addEventListener("resize", (e) => { // add winSizeFn here if you want call function on window resize })
 <div id="app">My app content</div>

nope, none of this will work.不,这些都行不通。 What you need is this!!!你需要的是这个!!!

Try this:尝试这个:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果屏幕宽度小于960像素,则将屏幕宽度添加到类中 - Add width of the screen to a class if screen width is less than 960 px 如果屏幕宽度小于 ...px,则仅执行一次操作 - Do something ONLY ONCE if screen width is less than ...px Bootstrap Google地图显示的像素不小于960px - Bootstrap google maps not showing less than 960px JS-如果窗口高度小于___px,请执行某些操作-此代码有什么问题? - JS - If window height is less than ___px, do something - What is wrong with this code? 当屏幕尺寸小于480px时,如何禁用jQuery功能? - How do I disable jQuery function when screen size is less than 480px? 航路点:如果偏移量小于某个值,则执行某些操作 - Waypoints: do something if offset is less than something 检查屏幕大小并在等于或大于 768 像素时执行某些操作 - Check Screen Size and Do Something if equal or greater than 768px 虽然 jQuery .toggle() 下拉菜单(宽度小于 991px) - though jQuery .toggle() dropdown (less than 991px width) 设备宽度小于1200像素时,scrollIntoView不起作用 - scrollIntoView not working when device width is less than 1200px JavaScript中屏幕分辨率小于767px时的addClass - addClass when the screen resolution is less than 767px in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM