Jquery扩展和收缩侧边栏保持窗口宽度尺寸

时间:2014-05-06 12:28:07

标签: jquery

我有一个侧栏,我总是希望有1/3窗口宽度或2/3窗口宽度,具体取决于用户是否点击了展开按钮

我有侧边栏工作,因为浏览器扩展但我需要它改为三分之二,如果他们点击展开但仍保持窗口宽度尺寸

问题是扩展未定义

小提琴就在这里 http://jsfiddle.net/ktcle/jPq9k/5/

$(document).ready(function() {

function checkWidth() {

    var $window = $(window);
    var windowsize = $window.width();
    var sideBarWidth = window.innerWidth / 3 * 1;
    var playerWidth = (window.innerWidth-sideBarWidth - 20);

    UpdatePlayerSize();
    UpdateSidebar();

    function UpdatePlayerSize(){
         $("#leftColumn").width(playerWidth);
     }

      function UpdateSidebar(){
         $("#sideBar").width(sideBarWidth);
     }

     function Expand()
    {
        sideBarWidth = window.innerWidth / 3 * 2;
        var sideBar = document.getElementById("sideBar");
        sideBar.style.width = sideBarWidth + "px";

        UpdatePlayerSize();
    }

    function Contract()
    {
        sideBarWidth = window.innerWidth / 3 * 1;
        var sideBar = document.getElementById("sideBar");
        sideBar.style.width = sideBarWidth + "px";

        UpdatePlayerSize();
    }
 };

checkWidth();
$(window).resize(checkWidth);
}); 

2 个答案:

答案 0 :(得分:2)

您正在使用在闭包之外无法访问的嵌套函数。最简单的解决方法是将ExpandContract方法附加到window范围:

http://jsfiddle.net/jPq9k/8/

function checkWidth() {

    var $window = $(window);
    var windowsize = $window.width();
    var sideBarWidth = window.innerWidth / 3 * 1;
    var playerWidth = (window.innerWidth-sideBarWidth - 20);

    // ...
    // etc (removed for brevity)
    // ... 

    //Just add these two lines to the end of your checkWidth function:
    window.Expand = Expand;
    window.Contract = Contract;

};

答案 1 :(得分:1)

我认为以下代码正在运行:

$('#expand').click(function(){
    $('#leftColumn').css({width: '33%'})
    $('#sideBar').css({width: '66%'})   
})

$('#contract').click(function(){
    $('#leftColumn').css({width: '66%'})
    $('#sideBar').css({width: '33%'})      
})

$('#contract').click()

我只是得到窗口宽度并改变了比例。我还编辑了一下你的HTML:

<div id="wrap">
    <div id="leftColumn"></div>
    <div id="sideBar">
        <button id="expand">expand</button>
        <button id="contract">contract</button>
    </div>
</div>

您可以查看new fiddle