如何在css中使用jQuery变量?

时间:2013-04-05 11:23:48

标签: javascript jquery css

如何使用存储在var height中的值作为margin-top的值?

<script>
    $(document).ready(function(){
      var height = $(window).height() / 2;

      $("a").click(function(){

        $("#loader").css({"margin-top:", ***height});

      });

    });
</script>

提前致谢...

5 个答案:

答案 0 :(得分:5)

像这样:

<script>
    $(document).ready(function(){
      var height = $(window).height() / 2;

      $("a").click(function(){

        $("#loader").css('margin-top', height+'px');

      });

    });
</script>

演示:http://jsfiddle.net/MtEjP/

答案 1 :(得分:2)

试试这个:

$("#loader").css('margin-top', height+'px');

答案 2 :(得分:0)

删除:并将其放在var height***之前:

$("#loader").css({"margin-top" : height});

这个可以用来设置多个css属性和属性:

$("selector").css({"cssattribute" : "cssproperty", 
                   "cssattribute" : "cssproperty"});

答案 3 :(得分:0)

尝试这样设置marginTop

  $('#loader').css('marginTop', height);

在这里查看演示..... http://jsfiddle.net/SUBqf/

答案 4 :(得分:0)

你可以用两种方式写出来:

$("#loader").css({"margin-top": height});

$("#loader").css("margin-top", height);

您必须选择具有多个attr用法的第一种方式。并用逗号(,)分隔它们。

Ex: $("#loader").css({"margin-top": height, "margin-bottom": height, "margin-left": "10px"});