2017-03-08 42 views
0

我試圖在用戶根據屏幕尺寸加載頁面時動態更改類標記的名稱。這裏是代碼:基於屏幕尺寸的HTML更改類名稱

<!DOCTYPE html> 
<html> 
<body onload="changeClass()"> 

<section class="example"> 
    <p>Hello</p> 
</section> 

<section class="example"> 
    <p>New section</p> 
</section> 

<script> 
function changeClass() { 
    var x = document.getElementsByClassName('example'); 
    var width = (window.innerHeight > 0) ? window.innerHeight : screen.Height; 
    console.log(width); 
    if(width <= 640) { 
     while(x.length > 0) { 
      x[1].className ='newClass'; 
     } 
    } else { 
     while(x.length > 0) { 
      x[0].className = "example"; 
     } 
    } 
} 
</script> 
</body> 
</html> 

但是,頁面被引入無限循環,無法加載數據。有沒有簡單的方法來設置基於屏幕大小命名的類?當頁面加載時,我可以使用「if條件」檢查嗎?我還包括一個JSFiddle。但我不知道這會有多大幫助。

+2

你爲什麼要用javascript來做這件事,而不是在CSS中進行媒體查詢?使用javascript處理樣式更改有點矯枉過正。 – Puzzle84

+0

您的最終目標是根據屏幕尺寸對元素應用不同的樣式嗎?或者還有另一個改變類名的理由嗎? –

+0

我只是尋找最簡單的方法來做到這一點。網上的人在建議Javascript。我只是想根據屏幕大小更改元素名稱。 – Dexstrum

回答

2

正如評論中所述,媒體查詢是實現您在此嘗試完成的最佳方式。

這就是說,要回答實際問題,因爲它現在代碼與您的代碼,您正在進入一個無限循環,因爲您正在使用while循環。數組的長度永遠不會達到零,因此您的while循環將永遠不會退出。

考慮使用以下代碼

if(width <= 640) { 
    for(var i = 0; i < x.length; i++) { 
     x[i].className ='newClass'; 
    } 
} 

很明顯,你需要改變兩個while循環。

儘管如此,我會強烈建議您使用媒體查詢,除非你有一個令人信服的理由不。

如果這個想法只是改變根據屏幕大小樣式,你可以用下面的除了你的樣式表

@media (max-width: 640px) { 
    .example { 
     ... styles to show on smaller screens .... 
    } 
} 
+0

謝謝。我知道如何使用媒體查詢。他們編寫代碼的方式需要修復。我正在尋找一個更簡單的方法來解決我面臨的這個特定問題。 – Dexstrum

0

有幾個,我可以在你的代碼中看到的問題,做到這一點。第一件事是你得到的屏幕寬度是不正確的。

它應該被修正如下。

var width = (window.innerWidth > 0) ? window.innerWidth : screen.Width; 

而第二件事是你根本不需要任何循環。只需遵循以下代碼就足以實現您所尋找的內容。

function changeClass() { 
    var x = document.getElementsByClassName('example'); 
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.Width; 
    console.log(width); 
    if(x.length > 0) { 
     if(width <= 640) { 
      x[1].className ='newClass'; 
     } else { 
      x[0].className = "example"; 
     } 
    } 
}