简体   繁体   中英

Change css background to a random background with jquery with animation

So I have a random quote generator and every time the user clicks New Quote button, the background of body and mainDiv that contains the quote changes. I want a animation to take place, i want it so that it fades out and the new background fades in over 100ms. i did some reading but my case is different since my background is randomly choosen from an array with math.random. here's my code.

<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]);
});

how do i animate change of background color (body and main div) so the previous background fades out in 100ms and new one comes in at 100ms? thanks

您可以在 css 中将过渡添加到“#mainDiv”和“body”以更改背景颜色和淡出以及在“targtP”div 中。

I don't see any colors there. Basically what I did is created an array with colors (of course put your 10 colors) and then i tell to the function which color from the array to choose. Why 10? it's maximum number that can be in numbers and seconds. I wrote these as a child for easy understanding and reading. Hope it was helpful.

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM