【问题标题】:JQuery animate margin-top using var not workingJQuery使用var为margin-top设置动画不起作用
【发布时间】:2016-03-06 03:51:37
【问题描述】:

我正在使用 JQuery 让我的 .wrapper div 在移动到 margin-top 后快速回到原来的 margin-top。原始边距顶部取决于浏览器高度。我试图通过将原始边距顶部值存储到一个变量中来做到这一点,并在我想要 .wrapper div 稍后恢复时将其用于 JQuery 动画。

$(document).ready(function() {
//Adjust .wrapper Margin-top to adjust position to 1/4 of Window Broswer Height
var marginWindowSpace = ($(window).height()) / 4;
$(".wrapper").css("margin-top", marginWindowSpace);

var originalMargin = $(".wrapper").css("margin-top").toString();
});

$(".title").click(function() {
    $("#results-container").empty();
    $(".wrapper").animate({
    'margin-top': originalMargin
    }, 200);
    $(".title-tag, .or, .random-article, .random-article-underline").fadeIn(500);
    $("footer").addClass("footer-pos1");
});

问题:为什么我的动画边距顶部不接受我的变量(存储原始边距顶部值的位置),即使转换为字符串?我不想使用静态值作为我的 margin-top。

如果您想查看应用代码,请点击此处。 http://codepen.io/myleschuahiock/pen/zqvvNZ

任何帮助表示赞赏!谢谢!

编辑:我将点击函数更改为 $('.go-back'),但 magin-top 的动画应该还是一样

【问题讨论】:

    标签: javascript jquery html css jquery-animate


    【解决方案1】:

    将整个$(".title").click(function(){}) 移入$(document).ready(function(){})

    问题的存在是因为在初始化$(".title").click(function(){})originalMargin 尚未设置,因为document 还不是ready

    【讨论】:

      【解决方案2】:

      这样做。你的动画部分有一些错误。margin-top 应该是正确的 marginTop 并且你的字符串应该转换为 int 并这样做。我作为一个例子来实现。希望这对你有帮助。

      <!DOCTYPE html>
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
      <title>Test</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
      </head>
      <style type="text/css">
       body{
        margin: 0;
        padding: 0;
       }
      
      div.testing{
        width: 100px;
        height: 100px;
        background-color: orange;
        margin-top: 100px;
      }
      
      div.two{
        width: 200px;
        height: 200px;
        background-color: green;
        position: 
      }
      
      </style>
      <body>
      
       <div class="testing"></div>
       <br><br>
       <h3 class="clk">Click me!</h3>
       <div class="two"></div>
      
      <script type="text/javascript">
      $(document).ready(function(){
        var one = $(".testing").css("margin-top").toString();
        var vaL = parseInt(one,10);
      
         $(".clk").click(function(){
          $(".two").animate({'marginTop':vaL+'px'},1000);
         });
      });
      
      </script>
      
      
      </body>
      </html>

      注意:

      var one = $(".testing").css("margin-top").toString();
      

      int 这部分以字符串形式获取margin-top 值。

      var vaL = parseInt(one,10);
      

      将其转换为整数。

      然后是动画部分

      $(".two").animate({'marginTop':vaL+'px'},1000);
      

      【讨论】:

        猜你喜欢
        • 2019-07-14
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多