判斷讀者瀏覽器類型和螢幕解析度,自動調用不同CSS

來源:互聯網
上載者:User
我們在設計網頁的時候一個比較頭痛的問題是究竟我們的瀏覽者的解析度是多少?如果使我們的瀏覽者能夠更好的去瀏覽到我的網頁,這個是我們設計前必須思考的問題。所以Leying在設計網頁的時候第一個想的是相容現在大多數瀏覽者的螢幕解析度,這裡頭有幾種最常用的方法:

    1、硬行把網頁先用表格框起來,框的解析度應該是在760-780象素,其餘的空間可以給一個背景圖或者空白.
    2、用自動縮放的方法也可以實現,這種方法比較古老,而且很簡單,這個不多說了;

    3、用自動判斷的方法。

    今天,就第三種方法來說說,如何來判斷出瀏覽者的螢幕解析度,根據不同的解析度給予讀者不同的瀏覽內容:

    網路上也有一些能自動判斷出你的瀏覽器是什麼類型或者什麼版本的代碼,整合過來。

  一、既判斷解析度,也判斷瀏覽器,使之成為判斷瀏覽器類型螢幕解析度自動調用不同CSS的代碼。

 <SCRIPT LANGUAGE="JavaScript">
<!--
if (window.navigator.userAgent.indexOf("MSIE")>=1)
{
var IE1024="";
var IE800="";
var IE1152="";
var IEother="";

ScreenWidth(IE1024,IE800,IE1152,IEother)
}else{
if (window.navigator.userAgent.indexOf("Firefox")>=1)
{
//如果瀏覽器為Firefox
var Firefox1024="";
var Firefox800="";
var Firefox1152="";
var Firefoxother="";

ScreenWidth(Firefox1024,Firefox800,Firefox1152,Firefoxother)
}else{
//如果瀏覽器為其他
var Other1024="";
var Other800="";
var Other1152="";
var Otherother="";
ScreenWidth(Other1024,Other800,Other1152,Otherother)
}
}

function ScreenWidth(CSS1,CSS2,CSS3,CSS4){
if ((screen.width == 1024) && (screen.height == 768)){
setActiveStyleSheet(CSS1);
}else{
if ((screen.width == 800) && (screen.height == 600)){
setActiveStyleSheet(CSS2);
}else{
if ((screen.width == 1152) && (screen.height == 864)){
setActiveStyleSheet(CSS3);
}else{
setActiveStyleSheet(CSS4);
}}}
}

function setActiveStyleSheet(title){
  document.getElementsByTagName("link")[0].href="style/"+title;
}
//-->
</SCRIPT>

    為了大家明白,這裡簡單解析一下:

引用內容var IE1024="";

var IE800="";

var IE1152="";

var IEother="";

    引號裡面分別填寫,使用者使用IE的時候並且解析度為1024*768,800*600,1152*864要使用的css檔案名稱。

 var Firefox1024="";

var Firefox800="";

var Firefox1152="";

var Firefoxother="";

    引號裡面分別填寫,使用者使用FireFox(一個也很流行的瀏覽器)的時候並且解析度為1024*768,800*600,1152*864要使用的css檔案名稱。

var Other1024="";

var Other800="";

var Other1152="";

var Otherother="";

    引號裡面分別填寫,使用者使用其他瀏覽器的時候並且解析度為1024*768,800*600,1152*864要使用的css檔案名稱。

  二、不判斷解析度,只判斷瀏覽器實現根據瀏覽器類型自動調用不同CSS。

 <SCRIPT LANGUAGE="JavaScript">
<!--
if (window.navigator.userAgent.indexOf("MSIE")>=1)
{
//如果瀏覽器為IE
setActiveStyleSheet("default.css");
}else{
if (window.navigator.userAgent.indexOf("Firefox")>=1)
{
//如果瀏覽器為Firefox
setActiveStyleSheet("default2.css");
}else{
//如果瀏覽器為其他
setActiveStyleSheet("newsky.css");
}
}

function setActiveStyleSheet(title){
  document.getElementsByTagName("link")[0].href="style/"+title;
}
//-->
</SCRIPT>

    解釋:(和前面的差不多)

      如果瀏覽器為IE,則調用default.css

      如果瀏覽器為Firefox,則調用default2.css

      如果瀏覽器為其他,則調用newsky.css

    使用方法:

      很簡單,放在 “</head>” 前面即可。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.