开发者

Trying to add css depending on browser width. Need Help (jQuery)

开发者 https://www.devze.com 2023-02-04 04:32 出处:网络
I\'m trying to add a css file depending on the browser width and not sure how to go about it. In this case, if the browser window is bigger than 1200 width it will add the css file. I know how to do

I'm trying to add a css file depending on the browser width and not sure how to go about it.

In this case, if the browser window is bigger than 1200 width it will add the css file. I know how to do this so it works with refresh but i want it so if the browser is being resized while activ开发者_运维技巧e on the page the css file's will change.

Here's what I have at the moment, i'm probably going in the wrong direction im not too sure:

<link rel="stylesheet" type="text/css" id="smallS" href="<?php bloginfo('template_directory'); ?>/css/default-960.css" /> 
<script>
    $(function(){
        $(window).resize(function(){
            var w = $(window).width();
            if (w > '1200') {
                document.write('<link rel="stylesheet" type="text/css" id="largeS" href="<?php bloginfo('template_directory'); ?>/css/default.css" />');
            }
            else {
                if($('#largeS').length > 0) {
                    $('#largeS').remove();
                }
            }
        });
    });
</script>

This is what I had before, but its not what I'm looking to do:

if ((screen.width>=1024))
    {
        document.write('<link rel="stylesheet" type="text/css"  href="<?php bloginfo('template_directory'); ?>/css/default.css" />');
    }

Any thoughts?


The problem is that document.write only works when the document is being first parsed, not later. You need to use DOM manipulation functions instead. Since you are using jQuery, this is greatly simplified:

$(window).resize(function(){
    if ($(window).width() > 1200) {
        if (!$('#largeS').length) {
            $('head').append('<link rel="stylesheet" type="text/css" id="largeS" href="<?php bloginfo('template_directory'); ?>/css/default.css" />');
        }
    }
    else {
        $('#largeS').remove();
    }
}).trigger('resize'); // invoke the handler immediately

Note that this uses $('head').append() and doesn't do an unnecessary check on the length of $('#largeS').


If using CSS3 is an option, mediaqueries will do this for you in a much nicer way. http://www.w3.org/TR/css3-mediaqueries/#width

Example:

<link rel="stylesheet" media="screen and (min-width: 1200px)" href="/css/default.css" />


Although you may not be able to code for CSS3 specifically, QuirksMode has an excellent article on using Javascript with media queries keeping standards in mind: http://www.quirksmode.org/blog/archives/2010/08/combining_media.html

There is also a jQuery plugin that makes media queries available for all browsers: project site | jquery site

0

精彩评论

暂无评论...
验证码 换一张
取 消