【JS】幅の算出

by tea4two

HTML

<link rel="stylesheet" href="http://reset5.googlecode.com/hg/reset.min.css">
<p id="ind"></p>
<div id="width480px">480</div>

CSS

#width480px {
    width: 480px;
    height: 30px;
    background-color: red;
}
#ind {
    padding: .5em;
    background-color: rgba(255,150,255,.6);
    position: fixed;
    right: 0;
    top: 0;
}

JavaScript

var flag = 'wide';
$(function() {
    var ws = $(window).width(),
        bg = $('#width480px');
    
    function narrow() {
        bg.css('background-color','yellow');
        flag = 'narrow';
    }
    function wide() {
        bg.css('background-color','red');
        flag = 'wide';
    }
    
    $('#ind').html(ws + ' px');
    
    if( ws <= 480 && flag !== 'narrow') {
        narrow();
    } else if( ws > 480 && flag !== 'wide') {
        wide();
    }
    
    $(window).on('resize', function() {
        var ws = $(window).width();
        console.log(ws);
        $('#ind').html(ws + ' px');
        
        if( ws <= 480 && flag !== 'narrow') {
            narrow();
        } else if( ws > 480 && flag !== 'wide') {
            wide();
        }
    });
    
});