【问题标题】:Exclude negative number from function to get and set margin从函数中排除负数以获取和设置边距
【发布时间】:2014-05-09 18:42:28
【问题描述】:

我有一个元素想要在页面中垂直居中。我想获取视口高度并从中减去页眉、页脚和主高度。结果数字将除以 3 并应用于元素的 margin-top。这工作正常,除非窗口垂直收缩时应用负数。

function getMargin() {
        var wHeight = $(window).height();
        var hHeight = $('header').height();
        var mHeight = $('main').height();
        var fHeight = $('footer').height();
        var height_diff = (wHeight - hHeight - mHeight - fHeight) / 3 + "px";
        //here is where its not working
        if ($(height_diff) >= '30px') {
            $('#content').css('margin-top', height_diff);
        } else {
            $('#content').css('margin-top', '40px');
        };
        console.log(height_diff);
    }
    $(window).resize(function(){
        getMargin();
    });

只要返回的数字(height_diff)大于 30px,就应用它作为边距,如果小于 30px 则使用默认值。我错过了什么?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这怎么会变成一个逻辑表达式?

     if ($(height_diff) >= '30px')
    

    不会的。左侧是存储数字的jquery元素,右侧是带有数字和文本的字符串。

    让我们解决显而易见的问题,看看我们会在哪里

    function getMargin() {
        var wHeight = $(window).height();
        var hHeight = $('header').height();
        var mHeight = $('main').height();
        var fHeight = $('footer').height();
        var height_diff = (wHeight - hHeight - mHeight - fHeight) / 3;
        //here is where its not working
        if (height_diff >= 30) {
            $('#content').css('margin-top', height_diff + "px");
        } else {
            $('#content').css('margin-top', '40px');
        };
        console.log(height_diff);
    }
    $(window).resize(function(){
        getMargin();
    });
    

    从我的角度来看会更好的东西

        var height_diff = Math.max(30,(wHeight - hHeight - mHeight - fHeight) / 3);
         $('#content').css('margin-top', height_diff + "px");
    

    如果需要其他逻辑则不需要,但这意味着如果 height_diff 小于 30,则使用 height_diff num 或 30,结果将是 30 而不是 40。

    【讨论】:

    • 最后的补充非常简洁,比我想象的要好得多。再次感谢您。
    【解决方案2】:

    您的问题是您正在对字符串进行数学比较。 >= '30px' 没有逻辑意义。

    改变

    var height_diff = (wHeight - hHeight - mHeight - fHeight) / 3 + "px";
    

    var height_diff = (wHeight - hHeight - mHeight - fHeight) / 3;
    

    改变

    if ($(height_diff) >= '30px') {
    

    if ($(height_diff) >= 30) {
    

    然后您可以稍后添加“px”(尽管您实际上不必这样做;如果省略单位后缀,jQuery 的 .css() 会推断像素。

    【讨论】:

    • “height_diff”是一个数字,所以我们不需要这样做“$(height_diff)”,只需要这个“height_diff”。 "$(height_diff)" 将返回一个具有 "height_diff" 变量值的数组。例如:“[40]”
    • 谢谢,我很感激。好答案
    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 2011-08-10
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多