2014-04-17 78 views
0

我正在處理一個類的任務,我必須創建一個外部JavaScript文件來檢查頁面的當前寬度並根據它改變鏈接的CSS樣式,每當頁面加載或調整大小時都會發生。通常情況下,我們會給出一個例子來將我們的任務分配給我們,但這次並不是這樣。使用JavaScript來改變基於頁面寬度的CSS樣式

本質上,我們將使用if ... then語句來更改樣式。我不知道該功能的適當聲明是什麼。我環顧四周,潛在的解決方案對於課堂來說太高級了,或者沒有完成我需要的東西。據我所知,我不能使用jQuery或CSS查詢。

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

+1

首先,您需要給它你最好的拍攝和後期你嘗試過什麼等等... – mccainz

+0

[window.onresize](https://developer.mozilla.org /en-US/docs/Web/API/Window.onresize)。 – lifetimes

+0

你應該改變CSS文件本身還是隻更換文件? – Richard

回答

-1

使用CSS和媒體查詢。通過js改變風格是個壞主意。

0

試試這個代碼

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 嘗試調整您的瀏覽器,並讓我知道如果這是你在找什麼。

+0

這是基本的想法,是的。唯一的區別是正在改變的是一個應用於HTML的外部CSS文檔。不過,我不知道這會有什麼不同。 – ghysterian

+0

你可以試試這個[點擊這裏!](http://www.w3.org/wiki/Dynamic_style_-_manager_CSS_with_JavaScript) –

+0

stylesheet = document.styleSheets [0]; stylesheet.insertRule(「。have-border {border:1px solid black;}」,0); –

0

//使用這個//

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(); 
};