【问题标题】:jquery, margin-top depending of $(window).height()jquery,margin-top 取决于 $(window).height()
【发布时间】:2011-08-10 10:24:03
【问题描述】:

我有一个 div 容器,它的上边距应该设置为 $(window).height() 的依赖项,所以首先我尝试了这样的事情:

        $("div#outerstart").css("margin-top",$(window).height() -805+"px");

效果很好,但 margin-top 不应该是负数,所以我尝试了这个:

        $("div#outerstart").css("margin-top",function () {
        if ($(window).height() < 805) {
            0+"px"  
        } else {
            $(window).height() -805+"px"
        }
    });

也可以

 if ($(window).height() < $(document).height()) {...

但它没有显示任何效果并且没有设置margin-top。你有什么建议吗?

【问题讨论】:

  • 使用return关键字?它的功能,而不是直接声明
  • @Marek Sebera:写一个答案而不是评论?

标签: jquery css


【解决方案1】:

让我们更改您的代码以使用函数中的 return 关键字

$("div#outerstart").css("margin-top",function () {
    if ($(window).height() < 805) {
        return "0px";  
    } else {
        return ($(window).height() -805)+"px";
    }
});

【讨论】:

  • 很高兴为您提供帮助,如果我的答案正确,请在答案左侧使用绿色标记。这就是这里的工作方式
  • 您可以通过将&lt; 更改为&gt; 来删除else 块...:p
【解决方案2】:

一个更简单的解决方案是使用Math.max 而不是匿名函数:

$("div#outerstart").css("margin-top", Math.max(0, $(window).height()-805)+"px");

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 2011-09-19
    • 2023-04-08
    • 2010-10-25
    • 2013-04-22
    • 2014-07-27
    • 2013-03-19
    • 1970-01-01
    • 2010-09-22
    相关资源
    最近更新 更多