问题
I have a series of jQuery scripts on my site that I want to only run if the users screen width is greater than 960px. I know that you can't detect screen size using php but is there a way to create something to this effect:
<? php
if [METHOD TO DETECT SCREEN SIZE] > 960px {
echo '<script src="js/nbw-parallax.js" type="text/javascript"></script>';
}
?>
回答1:
Why not use jQuery?
if( $(window).width() > 960 )
{
$.ajax({
url: 'js/nbw-parallax.js',
dataType: "script",
success: function() {
//success
}
});
}
回答2:
PHP is server side and can't grab your screen width and height.
You have to use javascript.
JQuery
if( $(window).width() > 960 ) {
$.getScript('js/nbw-parallax.js');
}
JavaScript
if( window.innerWidth > 960 ) {
//Your Code
}
回答3:
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<script src="js/nbw-parallax.js" type="text/javascript"></script>';
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
回答4:
you will have to use a javascript (or jQuery) function to generate the new script tags depending on the screen size. You will probably find this http://api.jquery.com/jQuery.getScript/ helpful.
回答5:
you should make the JS to detect the resolution and choose by itself whether it should run some code or not.
回答6:
You can have a javascript that sets a cookie containing the user's screen size. (Sure it won't work on the first request, but every subsequent request will work). Then in php you can get the value of the cookie.
来源:https://stackoverflow.com/questions/15142902/php-echo-statement-if-screen-is-a-certain-size