2013-12-10 38 views
-1

我建立一個使用網頁視圖從現有的移動網絡應用程序的Android應用程序。現有的移動網絡應用程序有一個標題圖形和一個使用無序列表的頁腳導航。與JavaScript的className問題發揮作用

由於Android應用具有天然的導航和已內置到應用程序的標題,使用移動網絡應用程序的頁面的網頁視圖時,Web應用程序頁眉和頁腳是在Android應用程序冗餘。由於移動網絡應用將用於blackberrys和windows phone等設備,因此我無法通用刪除頁眉和頁腳。此外,Web應用程序標頭使用了一些CSS,因此我需要確保它在移動Web應用程序中。

所以我決定嘗試使用javascript來檢測android操作系統,當它檢測到android操作系統時動態地爲頭和頁腳div分配一個類名,並且在CSS中引用類名不顯示這些div。如果操作系統不是Android,那麼它將創建指向移動Web應用程序中頭部所需CSS文件的樣式指針。

我不是JavaScript或CSS專家,所以我想出了一個簡單的測試,以確保這一切工作。一切正常,除非它似乎沒有將類名分配給div,以便在檢測到android操作系統時不顯示它。我知道這是檢測Android操作系統,因爲我在if語句中有一個警報,並且工作。我無法弄清楚我錯在哪裏。我使用Android 4.4和Chrome在Google Nexus 7上測試了此功能,並在Android 4.1.2上使用Chrome測試了摩托羅拉RAZR Droid。

測試代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 

<style> 
.android 
{ 
    display:none; 
} 
</style> 

<script language="javascript" type="text/javascript"> 

var isMobile = { 
    Android: function() { 
     return navigator.userAgent.match(/Android/i); 
    } 
}; 

var divID = "test"; 

var newClassName = "android"; 

function changeClass() { 

var divReference = document.getElementById(divID); 

divReference.className = newClassName; 

}; 

if(isMobile.Android()) 
    { 
     alert("android!"); 
     changeClass(); 

} 
else 
{ 
    alert("Not android!"); 
    document.write("<link rel='stylesheet' href='header.css' type='text/css'>"); 
} 

</script> 





<title>Untitled Document</title> 
</head> 

<body> 
<h1>Detect android device and hide second UL list below. If not android device, then hide the first UL list.</h1> 
<div class="notandroid"> 
<ul> 
<li>One</li> 
<li>two</li> 
<li>three</li> 
</ul> 
</div> 
<h2>This header is after the first UL list</h2> 

<div id="test"> 
<ul> 
<li>four</li> 
<li>five</li> 
<li>six</li> 
</ul> 
</div> 
<h2>This header is after the second UL list</h2> 

</body> 
</html> 
+1

你的''

0

要調用changeClass()元素之前,您試圖document.getElementById()與定義。請將您的代碼放入onload = function(){/*in here*/},或將您的腳本標籤放在身體的底部。簡而言之,必須先創建HTML,然後才能使用JavaScript獲取HTML。此外,XHTML中不支持document.write()http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite

+0

爲了記錄,'window'是隱含的,所以'onload'和'window.onload'是一樣的。 – PHPglue

0

有很多很好的理由,以避免瀏覽器的檢測。但是如果你決定繼續這樣做,你所遇到的主要問題是這個代碼在HEAD中運行,但是你正在尋找的DIV還不存在,就像它在主體中一樣。如果您希望document.write用於HEAD中的CSS,則可能需要在兩個塊中執行此操作。

+0

不應該在XHTML中使用'document.write()'。 http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite – PHPglue

+0

@PHPglue:有很多很好的理由來避免瀏覽器檢測,但OP有兩個。 –