Jumbotron animate()不起作用

时间:2017-04-28 05:02:16

标签: jquery html css twitter-bootstrap-3 jquery-animate

我一直在尝试使用jquery的animate(0方法)来改变jumbotron的颜色,但由于某种原因它无法正常工作。

$('.jumbotron').on('click', function() {
    console.log('click');
    $('.jumbotron').animate({
        backgroundColor: "rgb(229, 76, 76)"
    }, 1000);
    $('body').animate({
        backgroundColor: "#ff7373"
    }, 1000);
});

仅当我使用css选择器更改颜色时才有效。像这样,

$('#jumbo').on('click', function() {
    $( this ).css('background-color','#e54c4c');
});

任何人都知道为什么?

2 个答案:

答案 0 :(得分:0)

From docs:除非如下所述,否则所有动画属性都应设置为单个数值。大多数非数字属性无法使用基本的jQuery功能进行动画处理(例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color插件)。

因此,请尝试包含jquery color以使其正常工作。

$('.jumbotron').on('click', function() {
  console.log('click');
  // use this instead of using .jumbotron again
  $(this).animate({
    backgroundColor: "rgb(229, 76, 76)",
  }, 1000);
  $('body').animate({
    backgroundColor: "#ff7373"
  }, 1000);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/color/jquery.color-2.1.2.js"></script>

<div class="container">
  <div class="jumbotron">
    <h1>Bootstrap Tutorial</h1>
    <p>Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
  <p>This is some text.</p>
  <p>This is another text.</p>
</div>

如果您不想使用任何插件,则可以使用transition之类的,

$('.jumbotron').on('click', function() {
  console.log('click');
  // just toggle highlighted classs
  $(this).add('body').toggleClass('highlighted');
});
.jumbotron,body {
  -webkit-transition: background 1s linear;
  -moz-transition: background 1s linear;
  -ms-transition: background 1s linear;
  -o-transition: background 1s linear;
  transition: background 1s linear;
}
body.highlighted{background:#ff7373}
.jumbotron.highlighted{background:rgb(229, 76, 76)}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/color/jquery.color-2.1.2.js"></script>

<div class="container">
  <div class="jumbotron">
    <h1>Bootstrap Tutorial</h1>
    <p>Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
  </div>
  <p>This is some text.</p>
  <p>This is another text.</p>
</div>

答案 1 :(得分:0)

我的朋友,根据jQuery文档:http://api.jquery.com/animate/

  

动画属性和值

     

除非如下所述,否则应将所有动画属性设置为单个数值。大多数非数字属性无法使用基本jQuery功能进行动画处理(例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color插件)。除非另有说明,否则属性值被视为多个像素。可以在适用的情况下指定单位em和%。

您需要在jQuery之后(以及在您的脚本之前)包含https://github.com/jquery/jquery-color,以便能够为 backgroundColor 属性设置动画。

让我知道它是怎么回事;)