jQuery onload并使用cookie设置调整大小

时间:2012-04-18 18:46:59

标签: jquery class cookies resize pageload

寻找一些帮助来增加我已经拥有的东西。我工作的是一个onLoad和Resize交换到一个特定的类,它改变不同分辨率的网格。我需要的是设置一个cookie,以便在从一个页面到另一个页面时网格保持不变。

    // swaps the grid span names when the resolution goes below 1200px
    // or when page is loaded below 1200px

     $(window).bind("load resize", function(){

        var width = $(window).width(),
        bodycontent_grid = width < 1200 ? 'span8' :
                    width > 1200 ? 'span6' : '';
         rightcol_grid = width < 1200 ? 'span3' :
                    width > 1200 ? 'span5' : '';

        $('.bodycontent').removeClass('span6 span8').addClass(bodycontent_grid),
        $('.rightcol').removeClass('span3 span5').addClass(rightcol_grid);
    });

1 个答案:

答案 0 :(得分:0)

基于JS的解决方案不是很好(继续阅读),但无论如何我会尝试首先回答有关cookie的问题:

你可以使用某种jQuery cookie plugin或只是简单的JS,这有点难。 jQuery语法是:

$.cookie('name', 'value'); // storing cookie
$.cookie('name'); // reading cookie

使用它可以将源代码更改为:

function resizeContainer(var force=false) // additional parameter is used to force resetting cookie
{
    var width;
    if($.cookie('knownWidth') && !force) // if there's a cookie and we're not forcing reset, use width from cookie
    {
        width = $.cookie('knownWidth');
    }
    else
    {
        width = $(window).width();
        $.cookie('knownWidth', width);
    }
    var bodycontent_grid = width < 1200 ? 'span8' :
                width > 1200 ? 'span6' : '';
     rightcol_grid = width < 1200 ? 'span3' :
                width > 1200 ? 'span5' : '';

    $('.bodycontent').removeClass('span6 span8').addClass(bodycontent_grid),
    $('.rightcol').removeClass('span3 span5').addClass(rightcol_grid);
}

$(window).bind("load", function(){
    resizeContainer(); // onload use cookie
});
$(window).bind("resize", function(){
    resizeContainer(true); // when resizing force changing the cookie
});

在cource中,可以在服务器端访问cookie,然后可以在服务器端使用适当的类生成容器。

我必须说我不喜欢使用Cookie的解决方案。有很多关于responsive web design的讨论,所以为什么不使用CSS @media-queries

您可以在.css文件中执行以下操作:

@media only screen and (min-width : 1200px) {
    /* Styles when over 1200px */
}

@media only screen and (max-width: 1199px) {
    /* Styles when under 1200px */
}

顺便说一句,当你在http://bostonglobe.com/http://smashingmagazine.com时尝试调整浏览器窗口大小:)这是纯CSS!