使用jquery动态更改CSS显示属性并应用更改

时间:2013-10-10 20:19:59

标签: jquery html css

我正在尝试像jquery插件一样建立任务栏。我想在div中添加按钮。当我有几个可以放在父div中的按钮时,按钮大小可以设置为默认按钮大小。当要添加新按钮时,父div开始溢出,然后应调整按钮大小以适合父级。当它们再次被移除时,按钮应再次增加到其默认大小。这是我的代码

    _resizeChildren: function () {

        var self = this; // this is the <div> holding the taskbar
        var children = self.element.children();
        var len = children.length;
        var toolbarWidth = parseInt(self.element.width());
        var totalMargin = parseInt(children.css('marginLeft')) + parseInt(children.css('marginRight'));


        if (toolbarWidth / (len + totalMargin) >= $('#master').outerWidth()) //#master is a <div> holding the default size
        {
            self.element.css({'display': 'block'});
            self.element.css({'tableLayout': ''});
            children.css({'display': ''});
            children.outerWidth(parseInt($('#master').outerWidth()));
        }
        else {
            self.element.css({'display': 'table'});
            self.element.css({'tableLayout': 'fixed'});
            children.css({'display': 'table-cell'});

        }
    },

问题在于,当我运行此代码时,当新按钮添加到父div的宽度时,它们的大小与默认大小相符。当它们开始溢出时,旧按钮不会调整大小,从而为新按钮留下很小的空间,这些按钮被挤压在非常薄的空间中。

1 个答案:

答案 0 :(得分:0)

所以我终于找到了解决方案。那个if / else块应该是

  _resizeChildren: function () {

        var self = this; // this is the <div> holding the taskbar
        var children = self.element.children();
        var len = children.length;
        var toolbarWidth = parseInt(self.element.width());
        var totalMargin = parseInt(children.css('marginLeft')) + parseInt(children.css('marginRight'));


        if (toolbarWidth / (len + len * totalMargin) >= parseInt($('#master').outerWidth())) //#master is a <div> holding the default size
        {
            self.element.css({'display': 'block'});
            self.element.css({'tableLayout': ''});
            children.css({'display': ''});
            var maxWidth =$('#master').outerWidth();
            children.css('maxWidth', maxWidth);
        }
        else {
            self.element.css({'display': 'table'});
            self.element.css({'tableLayout': 'fixed'});
            children.css({'display': 'table-cell'});
            children.css('maxWidth', '');

        }
    },

现在,当我尝试仅使用一次调用.css()时尝试应用所有这些属性时,他们开始发生各种有趣的东西,比如任务栏调整大小,按钮消失等等。我没有太注意它。它像这样工作,我觉得它没关系。