【问题标题】:How to use jQuery variable in css? [closed]如何在 css 中使用 jQuery 变量? [关闭]
【发布时间】:2013-04-05 11:23:48
【问题描述】:

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

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

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

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

      });

    });
</script>

提前谢谢...

【问题讨论】:

  • 删除***?
  • 去掉***...否则你的代码是正确的
  • position 也可能有问题:您不能在任何块上设置 margin-top。

标签: javascript jquery css


【解决方案1】:

像这样:

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

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

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

      });

    });
</script>

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

【讨论】:

  • *** 只是为了显示使用高度的位置。但它不起作用。我的编辑器不喜欢这种语法:(
  • 去掉***并设置为评论,否则......
  • 我在回答中添加了一个演示。
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

      试试这个来设置 marginTop

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

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

      【讨论】:

        【解决方案5】:

        你可以用两种方式来写:

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

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

        您必须选择使用多属性的第一种方式。并用 逗号 (,) 分隔它们。

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

        【讨论】:

          猜你喜欢
          • 2013-07-10
          • 1970-01-01
          • 2013-02-18
          • 1970-01-01
          • 1970-01-01
          • 2013-10-08
          • 1970-01-01
          • 2013-01-30
          • 1970-01-01
          相关资源
          最近更新 更多