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

标签 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 的宽度时,它们的大小与默认大小很好。当它们开始溢出时,旧按钮不会调整大小,从而为新按钮留下非常小的空间,这些新按钮被挤压在右侧非常狭窄的空间中。

最佳答案

所以我终于找到了解决办法。 if/else block 应该是

  _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() 来应用所有这些属性时,它们开始发生各种有趣的事情,例如任务栏大小调整、按钮消失等。我没有太注意它。它像这样工作,我认为没关系。

关于jquery - 使用 jquery 动态更改 CSS 显示属性并应用更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19305447/

相关文章:

javascript - 在另一个 .js 文件中调用 javascript 方法

php - 重定向出目录

html - 元素在媒体查询 : 380px - but not when resized from bigger width and down to 380px 中的位置很好

javascript - 如何使用 CSS 和 JavaScript 制作可变主题

javascript - JQuery FancyBox 覆盖颜色

javascript - 如果我动态更改 html 内容,如何保持 CSS 样式?

jquery - 使用 jQuery 将表单序列化为对象数组

javascript - Powerange - 通过 javascript 更改值

javascript - 使用 Rangy 将键盘插入符号移动到元素的末尾

jquery - 如何防止用户在等待ajax响应时进行交互?