【问题标题】:css() not setting the height and widthcss() 没有设置高度和宽度
【发布时间】:2013-05-17 13:52:39
【问题描述】:

我正在尝试通过 jQuery .css() 为我的容器元素提供高度和宽度,但我的代码将其设置为窗口高度和宽度。谁能告诉我为什么代码不起作用?

下面是代码:

$(document).ready(function () {
    var H = $(window).height();
    var W = $(window).width();
    var h = W / 1.625;
    var w = H * 1.625;
    if (w > W) {
        $("#container").css("height", h + 'px').css("maxWidth", W + 'px;');
    else {
        $('#container').css("maxHeight", H + 'px').css("width", w + 'px;');
    }
});

【问题讨论】:

  • 这还取决于您为#container 设置的显示属性。另外你的代码有错误。
  • 使用 firefox 的 firebug 扩展。这是观察页面上发生的事情的好工具
  • 不要在没有必要的情况下以这样的方式调用.css();在一次调用中使用两个 args 调用它,如下所示:.css({height:h+'px', maxWidth: W+'px'});
  • #container 是块元素吗?
  • 可能的问题:你在'px;' 的maxWidth 和width 设置中的分号。这里不需要分号。

标签: javascript jquery css height width


【解决方案1】:

您的 if 语句缺少 },所以一开始就不起作用。变化:

if(w>W)  
{
    $("#container").css("height", h+'px').css("maxWidth", W+'px;');
    else
        ...

收件人:

if(w>W)  
{
    $("#container").css("height", h+'px').css("maxWidth", W+'px;');    
}                
else
    ...

此外,当您设置多个 CSS 属性时,您可以通过将属性作为对象传递来将它们组合成一个 CSS 方法:

if (w>W) 
{
    $("#container").css({height:h, maxWidth:w});
}
...

在大多数情况下,jQuery 会为您整理出px。有关更多信息,请参阅 jQuery 的 css() documentation。 :)

【讨论】:

  • 感谢您的帮助,但不知何故,多个 CSS 属性导致错误为未知令牌,问题是“;”以及我最终通过反复试验找到的牙套。
【解决方案2】:

您在 if 上缺少右大括号 },因此您的代码应如下所示,

if (w > W) {
    $("#container").css("height", h + 'px').css("maxWidth", W + 'px;');  
}
else {
    $('#container').css("maxHeight", H + 'px').css("width", w + 'px;');
}

您可以通过将 css 属性作为对象的一部分而不是链式传递来提高代码的可读性,因为当您将它们作为对象传递时,添加许多属性会很有帮助。

if (w > W) {
    $("#container").css({
         "height": h + 'px', 
         "max-width": W + 'px'
    });  
}
else {
    $("#container").css({
         "max-height": H + 'px', 
         "width": w + 'px'
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2012-07-24
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多