Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - How do I dynamically adjust css stylesheet based on browser width?

We're developing an open-source web app for arts teachers across the world to work together. We need a nice website that simply adjusts itself based on the active width of the browser, like google.org or barackobama.com does so well.

We can detect the browser, the OS, etc. but don't want to use any of that info. We just want four or five different stylesheets that are triggered when the browser width is adjusted.

So, for example, when you visit the app on a browser using a DESKTOP computer, you see the full app when the browser is full screen. Then, as the browser reduces its width the site immediately and dynamically changes its format to allow for universal compatibility.

We don't want our CSS to change based on browser type or original width, but instead want it to adjust ever millisecond based on the current width of the viewport -- regardless of whether or not it is a "mobile" device or a "tablet" machine or a "desktop" browser.

Curiously, I'm using Google Apps Script to host our web app, so it looks like any meta viewport tags are removed.

How can we introduce four or five different stylesheets based on the width of the current viewing browser window?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can either use CSS media queries, like so:

<link rel="stylesheet" media="screen and (min-device-width: 700px)" href="css/narrow.css" />
<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />
<link rel="stylesheet" media="screen and (max-device-width: 901px)" href="css/wide.css" />

Or jQuery, like so:

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

Both found from: http://css-tricks.com/resolution-specific-stylesheets/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...