使用jQuery切换容器的宽度

时间:2013-07-27 09:32:16

标签: jquery width toggle containers forum

我正在研究MyBB论坛软件的主题。 我想添加一个功能,其中宽度从容器的固定1000px扩展到流体宽度85%,反之亦然,使用jQuery慢动画。 我想要一个切换按钮,显示扩展 - 缩小按钮。 容器也应该支持cookie,因此当用户重新加载页面时,它将具有相同的宽度。 我尝试了Stackoverflow和Web上的许多解决方案但是徒劳无功。 感谢帮助。 提前致谢, 问候

以下是代码:

你好我想通了.... jquery切换,但我想添加cookie给它。 这是代码

        

     

$(document).ready(function(){
     $('#toggle-button')。click(function(){
         var toggleWidth = $(“#container”)。width()== 960? “85%”:“960px”;
         $('#container,.wrap')。animate({width:toggleWidth});
     });
  });

谢谢:)

1 个答案:

答案 0 :(得分:0)

以下是符合您要求的代码,请尝试以下代码:
HTML

<div id="container">this is container div</div>
<div class="wrp">this is wrp div</div>
<input type="button" value="toggle" id="toggle-button">  

CSS

#container {
   width:960px;
   background-color: red;
}
.wrp {
    width:1000px;
    background-color: green;
}

JS

$(document).ready(function () {
    var setWidth = $.cookie("width");
    if (typeof setWidth !== "undefined" && setWidth == "85%") {
        $('#container,.wrp').width(setWidth); // 85% width set using cookie
    } else if (typeof setWidth !== "undefined" && setWidth == "960px") {
        $('#container,.wrp').width(setWidth); // 960px,1000px(for wrp) width set using cookie
    }
    $('#toggle-button').click(function () {
        var toggleWidth = $("#container").width() == 960 ? "85%" : "960px";

        $('#container, .wrp').animate({
            width: toggleWidth
        });
        $.cookie('width', toggleWidth);
    });
});  

JSFIDDLE DEMO

注意:您必须将 jquery.cookie.min.js 添加到您的文件中才能获得Cookie