【问题标题】:Set height of an element on multiples of a number?在数字的倍数上设置元素的高度?
【发布时间】:2026-02-23 19:15:02
【问题描述】:

有没有什么方法可以通过 jquery 或 javascript 让一个元素将它的高度拉伸到一组特定的数字?我的意思是,因为它可以容纳更多的内容,它的高度只会遵循数字的模式(数字的倍数)。

假设以 100 的倍数... 一个 div 的高度随着它的延伸而变得更高,只会出现在这个系列中——200px、300px、400px 等。因此,如果它仅超出 200 的 1 个像素,它就会自动调整为 300。

很难解释。

我需要这个,因为我制作了一个带有撕裂边缘的垂直无缝图案,如果它完全显示每个图块,它看起来会非常完美。

我只知道基本的 jquery,我不知道如何解决这个问题。

我最诚挚的感谢谁愿意帮我查询!

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:
    var h = $('div').height();
    $('div').height( Math.ceil(h/100) * 100 );
    

    【讨论】:

    • 更好:$('div').height(function(i, h) { return Math.ceil(h / 100) * 100; });
    【解决方案2】:

    类似:

    $('element').css({ height : (0|(targetHeight + 99) / 100) * 100 });
    

    如果你想要它自动:

    $(function(){
        var $elem = $('#element')
        $elem.css({ height : (0|($(elem).height() + 99) / 100) * 100 });
    });
    

    【讨论】:

    • @cwolves 0|targetHeight 做什么?
    • @Šime Vidas - Math.floor((targetHeight + 99) / 100)
    • @cwolves 0|x 等于 Math.floor(x)?
    • @Šime Vidas - 是的,对于所有 | 是位运算符,JS 中的所有位运算都有一个隐式强制转换为整数
    • (5 | 9) === 13 // true 很有趣的东西。
    【解决方案3】:

    此函数将采用当前高度和您希望它捕捉到的单位编号,四舍五入到最接近的倍数。

    function snapHeight(height, multipleOf) {
        return multipleOf * Math.round(height / multipleOf);
    }
    

    例子:

    snapHeight(930, 100); // returns 900
    snapHeight(930, 50); // returns 950
    $('#element').height(snapHeight($('#element').height(), 100)); // in jQuery
    

    【讨论】:

      最近更新 更多