I'm using the following code to select a different stylesheet if the browser is above or below a certain height. Works great when you land on the page, or if you resize the window then refresh. But is there any way I can tweak this to select the correct style sheet on the fly, as the window is resized?
if (window.innerHeight <= 900) {
loadcss('css/container_sm.css');
} else {
loadcss('css/container_lg.css');
}
function loadcss(file) {
var el = document.createElement('link');
el.setAttribute('rel', 'stylesheet');
el.setAttribute('type', 'text/css');
el.setAttribute('href', file);
document.getElementsByTagName('head')[0].appendChild(el);
}
Perhaps it could be worth looking into an existing library such as twitter bootstrap ? They offer responsive stylesheets out of the box that adjust automatically when the window is resized.
You can add event handle to you script. With jquery
$(window).resize(function(){
if (window.innerHeight <= 900) {
loadcss('css/container_sm.css');
} else {
loadcss('css/container_lg.css');
}
})
without jquery window.onresize = function(){}
Here is what we have to do:
container_lg.css
or container_sm.css
and remove it. Here is the code:
var SMALL = 0;
var BIG = 1;
var previousSize = null;
var thresholdHeight = 400;
var firstCall = true;;
function selectCSS()
{
if ((previousSize == null || previousSize == BIG) &&
window.innerHeight <= thresholdHeight) {
removeOldCSS();
loadNewCSS('css/container_sm.css');
previousSize = SMALL;
} else if ((previousSize == null || previousSize == SMALL) &&
window.innerHeight > thresholdHeight) {
removeOldCSS();
loadNewCSS('css/container_lg.css');
previousSize = BIG;
}
}
function removeOldCSS(file)
{
var headNode = document.getElementsByTagName('head')[0];
var linkNodes = document.getElementsByTagName('link');
for (var i = 0; i < linkNodes.length; i++) {
var linkNode = linkNodes[i];
if (linkNode.parentNode == headNode &&
linkNode.href.search(/css\/container_(?:sm|lg).css$/) >= 0) {
headNode.removeChild(linkNode);
}
}
}
function loadNewCSS(file)
{
var el = document.createElement('link');
el.setAttribute('rel', 'stylesheet');
el.setAttribute('type', 'text/css');
el.setAttribute('href', file);
document.getElementsByTagName('head')[0].appendChild(el);
}
window.onload = selectCSS;
window.onresize = selectCSS;
Try this:
document.body.onresize = function (){
if (window.innerHeight <= 900) {
loadcss('css/container_sm.css');
} else {
loadcss('css/container_lg.css');
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.