簡體   English   中英

使用JavaScript根據頁面寬度更改CSS樣式

[英]Using JavaScript to change CSS style based on page width

我正在為一個類進行分配,在該類中,我必須制作一個外部JavaScript文件,該文件檢查頁面的當前寬度並基於該寬度更改鏈接的CSS樣式,並在頁面加載或調整大小時發生這種情況。 通常,我們會給出一個示例,以我們的分配為基礎,但是這次並非如此。

本質上,我們將使用if ... then語句來更改樣式。 我不知道該函數將使用什么適當的語句。 我環顧四周,潛在的解決方案要么太高級了,要么不滿足我的需要。 據我所知,我不能使用jQuery或CSS查詢。

如果有人能給我一個例子,說明我將如何寫出來,我將非常感激。

試試這個代碼

HTML是

<div id="resize" style="background:red; height: 100px; width: 100px;"></div>

javascript是

var resize = document.getElementById('resize');
window.onresize=function(){
    if(window.innerWidth <= 500) {
        resize.style = "background:blue; height: 100px; width: 100px;";
    }
    else {
        resize.style = "background:red; height: 100px; width: 100px;";
    }
};

我已經為您創建了一個示例,請在這里查看TESTRESIZE嘗試調整瀏覽器的大小,並讓我知道您是否在尋找它。

//用這個//

function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
    width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
    width = document.documentElement.clientWidth;
} else if (document.body) {
    width = document.body.clientWidth;
}
// now we should have it
if (width < 799) {
    document.getElementById("CSS").setAttribute("href",     "http://carrasquilla.faculty.asu.edu/GIT237/smallStyle.css");
} else {
    document.getElementById("CSS").setAttribute("href", "http://carrasquilla.faculty.asu.edu/GIT237/largeStyle.css");
}
}

// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
window.onload = function () {
adjustStyle();
};

使用CSS和媒體查詢。 用js更改樣式是個壞主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM