如何在JQuery中使用变量设置CSS属性?

时间:2015-07-21 18:23:52

标签: javascript jquery html css

我需要将width的CSS属性设置为与浏览器当前宽度相同的大小。为此,我做了var setWidth = $(window).width(),但我不知道如何将其应用于我当前的代码,这是这样的:

$(document).ready(function(){
    $("#backgroundImg").css("width", ""); 
});

有没有办法做到这一点?我是JQuery的新手,所以我可能只是非常业余。

4 个答案:

答案 0 :(得分:7)

试试这个

$(document).ready(function() {
    var setWidth = $(window).width();
    $("#backgroundImg").css("width", setWidth + 'px'); 
});

或者您可以使用$.width

$(document).ready(function() {
    $('#backgroundImg').width( $(window).width() )
});

答案 1 :(得分:0)

将代码更新为以下

  for (int line = n - 1; line >= 1; line--)
  {
      for (int spaces = n - line; spaces >= 0; spaces--)
          System.out.print(" ");

      for(int i = 1; i < line + line; i++)
          System.out.print("*");

      System.out.println();
  }

  keyboard.close();

答案 2 :(得分:0)

一个选项:$(“#backgroundImg”)。css(“width”,“100%”);

使用变量选项do:var setWidth = $(window).width()+'px';

所以你的代码将是

$(document).ready(function(){
$("#backgroundImg").css("width", setWidth); 

});

答案 3 :(得分:0)

这应该使背景与浏览器的当前宽度匹配:

$( "#backgroundImg" ).width( setWidth )

Source