改变css背景与jquery的动画随机背景



所以我有一个随机报价生成器,每次用户单击New quote按钮时,body的背景和包含报价的mainDiv都会发生变化。我想要一个动画发生,我想让它淡出,新的背景淡出超过100毫秒。我做了一些阅读,但我的情况是不同的,因为我的背景是从math.random数组中随机选择的。这是我的代码。

<body>
  <div id="mainDiv" class="colorChange">
    <button id="newQuote" class="btn btn-danger">New Quote</button>
    <div id="targetP"></div>
  </div>
</body>
var divBackground, bodyBackground,quoteButton,targetP,number,sec;
    targetP=$("#targetP").val();
    $("#newQuote").click(function () {
    number=Math.floor((Math.random() * 10) + 1);
    sec=Math.floor((Math.random() * 10) + 1);
    $("#mainDiv").css("background-color",colors[number]);
    $("body").css("background-color",colors[sec]);
    $("#targetP").html(quotes[number]);
});

我如何动画改变背景颜色(主体和主div),使以前的背景在100ms内淡出,新背景在100ms内出现?由于

你可以在css中添加过渡到"#mainDiv"one_answers"body"来改变背景色和淡出,在" targetp "div中

我没有看到任何颜色。基本上我所做的就是创建一个有颜色的数组(当然是你的10种颜色),然后我告诉函数从数组中选择哪一种颜色。为什么10 ?这是可以用数和秒表示的最大数字。为了便于理解和阅读,我小时候就写了这些。希望对您有所帮助。

<script>
  var divBackground, bodyBackground, quoteButton, targetP, number, sec;
var colors = ["red","green","blue","black","navy","pink","red","silver","blue","black","silver","pink"];
function myFunction(){
  number = Math.floor((Math.random() * 10) + 1);
  sec = Math.floor((Math.random() * 10) + 1);
  document.getElementById('mainDiv').style.backgroundColor =  colors[number];
  document.getElementById("body").style.backgroundColor =  colors[sec];
};
</script>
<style>
body{
  transition: 1s;
}
#mainDiv{
  width: 200px;
  height: 200px;
  transition: 1s;
}
</style>
</head>
  <body id="body">
    <div id="mainDiv" class="colorChange">
      <button id="newQuote" class="btn btn-danger" onclick="myFunction()">New Quote</button>
      <div id="targetP"></div>
    </div>

最新更新