Jquery动画不起作用

时间:2017-08-15 05:55:28

标签: javascript jquery html css html5

我尝试了我的代码,但它无法正常工作请检查以下代码:



<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
  <button>Click me</button>
  <p style="width: 90px; background-color: #40FF08">This is a test peragraph</p>
</body>

</html>
<script>
  $(document).ready(function() {
    $("button").click(function() {
      $("p").animate({
        left: '400px'
      });
    });
  });
</script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

添加position: relative,你的动画就可以了。

p {
  width: 90px;
  background-color: #40FF08;
  position: relative; <-- like this
}

$(document).ready(function() {
  $("button").click(function() {
    $("p").animate({
      left: '400px'
    });
  });
});
p{
width: 90px;
background-color: #40FF08;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>
<p>This is a test peragraph</p>

答案 1 :(得分:2)

这是因为position元素的p属性为 static ,而left不适用于 static 元素 - 将其更改为relative并且它有效 - 请参阅下面的演示:

$(document).ready(function() {
  $("button").click(function() {
    $("p").animate({
      left: '400px'
    });
  });
});
p {
  width: 90px;
  background-color: #40FF08;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button>Click me</button>
<p>This is a test peragraph</p>