我正在尝试构建一个类似 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/