我想让我的 html 元素变成不同的背景颜色,但我希望它有一个淡入淡出的过渡。
function changeBackground() {
console.log("changeBackground() function is working");
var backgrounds = ["navy", "blue", "aqua", "teal", "olive", "green", "lime", "yellow", "orange", "red", "maroon", "fuchsia", "purple"];
var randomBG = backgrounds[Math.floor(Math.random() * backgrounds.length)];
$("html").animate({backgroundColor: randomBG}, "slow");
console.log(randomBG);
}
我在第 5 行遇到了一些问题。这里有些东西不工作,我的代码坏了。这是执行此操作的正确方法吗/我应该使用 fadeIn()(以及如何使用)吗?
根据animate
方法的描述
可以动画的属性:
backgroundPositionX
backgroundPositionY
borderWidth
borderBottomWidth
borderLeftWidth
borderRightWidth
borderTopWidth
borderSpacing
margin
marginBottom
marginLeft
marginRight
marginTop
outlineWidth
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
height
width
maxHeight
maxWidth
minHeight
minWidth
fontSize
bottom
left
right
top
letterSpacing
wordSpacing
lineHeight
textIndent
因此,背景颜色无法设置动画。但是,您可以为所需的元素指定 transition
属性。然后您可以更改元素的颜色,它将使用浏览器内置动画进行动画处理。
像那样
function changeBackground() {
console.log("changeBackground() function is working");
var backgrounds = ["navy", "blue", "aqua", "teal", "olive", "green", "lime", "yellow", "orange", "red", "maroon", "fuchsia", "purple"];
var randomBG = backgrounds[Math.floor(Math.random() * backgrounds.length)];
$("html").css('background-color',randomBG);}
$('#click').click(function () {changeBackground()});
html {
transition: background-color 5s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">Click to change the colour</button>
我是一名优秀的程序员,十分优秀!