jQuery - 计算 minWidth

标签 jquery variables css

View jsFiddle

尝试设置 min-Width<menu>通过计算所有 <command> 的总宽度<menu> 内的元素。我尽力在下面jQuery中弄清楚了:

$(document).ready(function() {
    $('menu').each(function() {

        var minWidth;

        $('menu command').each(function() {
            minWidth = minWidth + $(this).outerWidth(); 
        });

        $(this).css('min-width', minWidth);
    });
});

这是 HTML 的格式:

<menu>
    <command class="less" />
    <command class="more" />

    <div class="space"></div>

    <command class="save" />
    <command class="vote" />
    <command class="send" />
</menu>

The div.space is just a seperator that I'm going to code later to split the commands across the full length.

我的代码目前没有错误。

View jsFiddle

最佳答案

定义 minWidth 变量时,您忘记将其设置为 0。您还忘记在设置 CSS 时在数字后面添加“px”。这是您的代码,正在运行:

$(document).ready(function() {
    $('menu').each(function() {

        var minWidth = 0;

        $('menu command').each(function() {
            minWidth = minWidth + $(this).outerWidth();
        });

        $(this).css('min-width', minWidth + 'px');
    });
});

http://jsfiddle.net/kkBRE/5/

关于jQuery - 计算 minWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829140/

相关文章:

javascript - 为什么我无法访问 html 元素的属性值之一,但我可以使用 jQuery 访问其他元素的属性值?

javascript - 当我用ajax获取数据时我无法发布它

php - 如果我用引用覆盖原始变量,内部会发生什么?

python - 如何在Python中创建未知数量的变量

javascript - 在 CSS3 旋转后检索元素的正确 offsetTop 和 offsetLeft

javascript - 是否可以响应式地换行表行?

javascript - 如何使用 jquery 获取特定文本框中的值并使用 onfocus 将其存储到变量中

javascript - 未捕获的范围错误 : Maximum call stack size exceeded (jquery-1. 12.4)

variables - 地形变量中的 map 内的 map

html - 使用带 rails 的 Twitter Bootstrap 时按钮未调整大小