Как получить разрешение экрана посетителя в javascript и / или php?

Я хотел бы узнать разрешение экрана посетителя, посетившего мою страницу, чтобы я мог правильно сделать обложку jQuery толщиной около 75% экрана.

Решения вопроса или помощь в решении моей проблемы приветствуются!

Что заставляет вас думать, что у людей всегда есть окно браузера, максимизированное до того же размера, что и их экран? Я этого не делаю, и я не единственный.

Вы хотите покрыть 75% своего окна . Это можно сделать с помощью CSS; если рассматриваемый элемент является дочерним элементом элемента body, то

#box { position: absolute; top: 12.5%; left: 12.5%; width: 75%; height: 75%; } 

вероятно, сделает это (я его еще не протестировал).

EDIT: Я сейчас тестировал его, добавляя

 html, body { width: 100%; height: 100%; } 

и он работал как ожидалось, по крайней мере в Firefox 3.5 🙂

В JavaScript это:

 screen.width screen.height 

Но PHP не имеет доступа к клиенту. Поэтому вам нужно передать значения, собранные JavaScript, в ваш PHP-скрипт.

Кроме того, не каждый пользователь имеет свои окна в полноэкранном режиме. Поэтому вам лучше использовать доступную ширину / высоту окна .

Если вы используете jQuery, есть кросс-браузерное решение для получения размера окна браузера:

 var browserWidth = $(window).width(); var browserHeight = $(window).height(); 

вы можете попробовать этот размер окна Hack, и он говорит обо всех браузерах. (включая немой IE6)

 var width = document.body.offsetWidth; var bodyHeight = document.body.scrollHeight; var height = (typeof window.innerHeight !== "undefined")? window.innerHeight : (document.documentElement)? document.documentElement.clientHeight : document.body.clientHeight; height = (bodyHeight > height)? bodyHeight : height; 

Ну, после всей работы над этим вопросом я улучшу свой ответ.

Сначала некоторые выводы, которые были получены с большим трудом:

  1. [Нет файлов cookie .. забудьте об этом] Не делайте ничего подобного настройке переменных сеанса на сервере. В противном случае evrey время загрузки вашей страницы новый файл сеанса будет создан на serveride (файл является обычным обработчиком для сеансов), и каталог будет накапливаться с файлами, и вы по-прежнему не сможете отслеживать сеанс. Если вы найдете способ, мы все будут рады услышать это.

  2. [Нет файлов cookie .. забыть причудливые скрипты!] Без файлов cookie у вас может быть некоторый успех, например, с помощью метода отслеживания ip и т. Д., Но все же есть ошибки, и там будет ситуация, когда он появится.

  3. [Нет файлов cookie .. не купите файлы cookie] Если вы можете работать с вашими страницами без файлов cookie, то в противном случае это не стоит.

Что касается разрешения экрана, мой скрипт ниже может сделать это:

  1. Немедленно отображать информацию для всех 4 комбинаций cookie и js.
  2. Если пользователь вносит изменения, позволяющие отключить js или cookie, эти изменения немедленно идентифицируются скриптом.
  3. Я использовал хром плюс и любое изменение, которое я сделал, в любой комбинации сразу было идентифицировано. Он работал даже без удаления старых файлов cookie.

Это мой скрипт, он включает функцию dbg () только для отладки, я попытался сделать ее ошибкой, но тест для себя!

 <?PHP class prereqCls { //change this private $self="http://localhost/prereq.php"; private $jsCookie=""; function __construct() { //entering conditions, an autosubmit bttn fetches the rest fields not it self $enter=false; if(isset($_GET['rl']))$enter=true; if(!isset($_POST['js_alive']) and !isset($_POST['noJsBttn']))$enter=true; if($enter) { dbg("Now writing a php cookie..","construct"); setcookie('cookie_alive',1,time()+3600);//set it for 1 hour dbg("Now calling Js..","construct"); $this->getSettings(); return; } //identify setting $this->identifySett(); //display the appropriate link if($this->jsCookie!=="") echo "<a href=".$this->self."?rl=1 >If you enebled {$this->jsCookie}, don't refresh but click here to load the new settings!</a>"; else echo "<a href=".$this->self."?rl=1 >Click only this to relaod the page..</a>"; //display the cookie if set if(isset($_COOKIE['cookie_alive'])) { echo "<br><br>Well this is the cookie!<br>"; print_r($_COOKIE); } }//method private function identifySett() { if(isset($_POST['js_alive']) and isset($_COOKIE['cookie_alive'])) dbg("Both js and cookies are enabled!","construct"); elseif(isset($_POST['js_alive']) and !isset($_COOKIE['cookie_alive'])) {dbg("Js is enabled cookies not!","construct"); $this->jsCookie="Cookies";} elseif(!isset($_POST['js_alive']) and isset($_COOKIE['cookie_alive'])) {dbg("Js is not enabled, cookie is!","construct"); $this->jsCookie="Javascript";} elseif(!isset($_POST['js_alive']) and !isset($_COOKIE['cookie_alive'])) {dbg("Js and cookies are not enabled!","construct"); $this->jsCookie="Javascript and Cookies";} } //php method begins private function getSettings() { ?> <html> <head> <script type="text/javascript"> //the values entered to cookie by js will be seen by php immediately on reload!!! //write the screen data to the cookie too var exdays = 365; var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(screen.width) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="scr_width=" + c_value; var c_value=escape(screen.height) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="scr_height=" + c_value; var c_value=escape(1) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="js=" + c_value; //autosubmit the form in milliseconds window.setTimeout("document.getElementById('scrForm').submit();",0); </script> </head> <body > <form id="scrForm" action="<?PHP echo $this->self;?>" method="post"> <!--If Js is enabled the appropriate bttn will be shown--> <script type="text/javascript"> document.write('<input type="hidden" name="js_alive" value="1">'); document.write('<input type="submit" name="JsBttn" value="Go">'); </script> <noscript> Some trouble trying to find screen settings.. Click to continue! <input type="submit" name="noJsBttn" value="Go"> </noscript> </form> </body> </html> <?PHP } ////////////////////php method ends }/////////////class //debuger function dbg($str,$caller) { echo "<br> [{$str}][{$caller}]<br>"; $log="Log Begins:---".date('YMd h:i:s')."--------[CALLER]{$caller}----------\n"; $log.= $str."\n"; $log.= "Log Ends:-------------------------------------------------------\n\n"; $fh=fopen("log_errors.log","a"); fwrite($fh, $log); fclose($fh); } ///////////////////// //make the class alive $alive = new prereqCls(); ?> . <?PHP class prereqCls { //change this private $self="http://localhost/prereq.php"; private $jsCookie=""; function __construct() { //entering conditions, an autosubmit bttn fetches the rest fields not it self $enter=false; if(isset($_GET['rl']))$enter=true; if(!isset($_POST['js_alive']) and !isset($_POST['noJsBttn']))$enter=true; if($enter) { dbg("Now writing a php cookie..","construct"); setcookie('cookie_alive',1,time()+3600);//set it for 1 hour dbg("Now calling Js..","construct"); $this->getSettings(); return; } //identify setting $this->identifySett(); //display the appropriate link if($this->jsCookie!=="") echo "<a href=".$this->self."?rl=1 >If you enebled {$this->jsCookie}, don't refresh but click here to load the new settings!</a>"; else echo "<a href=".$this->self."?rl=1 >Click only this to relaod the page..</a>"; //display the cookie if set if(isset($_COOKIE['cookie_alive'])) { echo "<br><br>Well this is the cookie!<br>"; print_r($_COOKIE); } }//method private function identifySett() { if(isset($_POST['js_alive']) and isset($_COOKIE['cookie_alive'])) dbg("Both js and cookies are enabled!","construct"); elseif(isset($_POST['js_alive']) and !isset($_COOKIE['cookie_alive'])) {dbg("Js is enabled cookies not!","construct"); $this->jsCookie="Cookies";} elseif(!isset($_POST['js_alive']) and isset($_COOKIE['cookie_alive'])) {dbg("Js is not enabled, cookie is!","construct"); $this->jsCookie="Javascript";} elseif(!isset($_POST['js_alive']) and !isset($_COOKIE['cookie_alive'])) {dbg("Js and cookies are not enabled!","construct"); $this->jsCookie="Javascript and Cookies";} } //php method begins private function getSettings() { ?> <html> <head> <script type="text/javascript"> //the values entered to cookie by js will be seen by php immediately on reload!!! //write the screen data to the cookie too var exdays = 365; var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(screen.width) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="scr_width=" + c_value; var c_value=escape(screen.height) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="scr_height=" + c_value; var c_value=escape(1) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie="js=" + c_value; //autosubmit the form in milliseconds window.setTimeout("document.getElementById('scrForm').submit();",0); </script> </head> <body > <form id="scrForm" action="<?PHP echo $this->self;?>" method="post"> <!--If Js is enabled the appropriate bttn will be shown--> <script type="text/javascript"> document.write('<input type="hidden" name="js_alive" value="1">'); document.write('<input type="submit" name="JsBttn" value="Go">'); </script> <noscript> Some trouble trying to find screen settings.. Click to continue! <input type="submit" name="noJsBttn" value="Go"> </noscript> </form> </body> </html> <?PHP } ////////////////////php method ends }/////////////class //debuger function dbg($str,$caller) { echo "<br> [{$str}][{$caller}]<br>"; $log="Log Begins:---".date('YMd h:i:s')."--------[CALLER]{$caller}----------\n"; $log.= $str."\n"; $log.= "Log Ends:-------------------------------------------------------\n\n"; $fh=fopen("log_errors.log","a"); fwrite($fh, $log); fclose($fh); } ///////////////////// //make the class alive $alive = new prereqCls(); ?> 

После определения экрана вы можете выглядеть так:

В вашем файле view.htm (любой) включается такой стиль:

  <link rel="stylesheet" href="style.php" /> 

то ваш стиль.php может быть таким:

 <?php header("Content-type: text/css"); $width = $_COOKIE['scr_width']; $height = $_COOKIE['scr_height']; element 1 width is let's say 0.2 of width element 2 width is let's say 0.7 of width big container (it could be a single cell table) width=all other elements width or if image height is>image width then this variable will be ... or image path is random or image path dynamic or ... etc etc endless possibilities, you can do anything here in this css stylesheet. ?> then [still on the same file, Yes css and php together!] for example apply the variables, only simple variables work down here, keep calculations for above. #smImgZoom { width:<?PHP echo $zoomerImgWidth."px;";?> height:<?PHP echo $zoomerImgHeight."px;";?> padding:10px ; } etc etc this is how I do it so html remain clear, css clear, calculations separated. 

Просто по-моему, не нужно хорошо!

эй, я узнал, что есть полезная тема, связанная с этим,

Разница между screen.availHeight и window.height ()