我試圖在用戶根據屏幕尺寸加載頁面時動態更改類標記的名稱。這裏是代碼:基於屏幕尺寸的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。但我不知道這會有多大幫助。
你爲什麼要用javascript來做這件事,而不是在CSS中進行媒體查詢?使用javascript處理樣式更改有點矯枉過正。 – Puzzle84
您的最終目標是根據屏幕尺寸對元素應用不同的樣式嗎?或者還有另一個改變類名的理由嗎? –
我只是尋找最簡單的方法來做到這一點。網上的人在建議Javascript。我只是想根據屏幕大小更改元素名稱。 – Dexstrum