jQuery - 根据屏幕大小执行脚本

时间:2022-01-11 20:24:39

Is it possible to only run certain jQuery scripts if the screen/device size is above xxx pixels wide?

如果屏幕/设备大小超过xxx像素宽,是否可以只运行某些jQuery脚本?

So, for example, I only want to run a slideshow when people are viewing the site on devices bigger than 1024px. If someone visits on a mobile I just want all the images to display stacked on top of each other...

因此,例如,当人们在大于1024px的设备上查看网站时,我只想播放幻灯片。如果有人在手机*问我只想让所有图像叠加在一起...

4 个解决方案

#1


51  

You can use $(window).width()

你可以使用$(window).width()

if($(window).width() >= 1024){
  // do your stuff
}

Demo ---> http://jsfiddle.net/fh2eC/1/

演示---> http://jsfiddle.net/fh2eC/1/

#2


20  

If you want to check width size after windows is resized then:

如果要在调整窗口大小后检查宽度大小,则:

$(window).resize(function() {
    if( $(this).width() > width ) {
        // code
    }
});

#3


4  

You might also consider a library like https://github.com/paulirish/matchMedia.js/

您可能还会考虑像https://github.com/paulirish/matchMedia.js/这样的库。

if (matchMedia('only screen and (max-width: 480px)').matches) {
  // smartphone/iphone... maybe run some small-screen related dom scripting?
}

#4


-3  

You can use a function then set an interval for it to check the size every 10 mill....... Here....

您可以使用一个功能,然后设置一个间隔,以检查每10毫米的大小.......这里....

function change(){
document.getElementById("p").innerHTML = window.innerWidth;
}

setInterval(change, 10);

#1


51  

You can use $(window).width()

你可以使用$(window).width()

if($(window).width() >= 1024){
  // do your stuff
}

Demo ---> http://jsfiddle.net/fh2eC/1/

演示---> http://jsfiddle.net/fh2eC/1/

#2


20  

If you want to check width size after windows is resized then:

如果要在调整窗口大小后检查宽度大小,则:

$(window).resize(function() {
    if( $(this).width() > width ) {
        // code
    }
});

#3


4  

You might also consider a library like https://github.com/paulirish/matchMedia.js/

您可能还会考虑像https://github.com/paulirish/matchMedia.js/这样的库。

if (matchMedia('only screen and (max-width: 480px)').matches) {
  // smartphone/iphone... maybe run some small-screen related dom scripting?
}

#4


-3  

You can use a function then set an interval for it to check the size every 10 mill....... Here....

您可以使用一个功能,然后设置一个间隔,以检查每10毫米的大小.......这里....

function change(){
document.getElementById("p").innerHTML = window.innerWidth;
}

setInterval(change, 10);