gpt4 book ai didi

javascript - 使用 JavaScript 在单击时修改 css BackgroundSize

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:24 24 4
gpt4 key购买 nike

我正在使用 css 动画制作动画背景。我可以在单击按钮时将其关闭,但它不适用于第二次单击。我知道这是可能的,因为我在控制台中输入了该函数并且它起作用了。

我已经尝试过 switch 语句和条件语句。

我不想重新加载页面,而是使用相同的按钮再次进行 Action 。

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<head>
<title>a</title>
<style>
body {
font-family: verdana, arial, sans-serif;
font-size: 14px;
margin: 0;
width: 100%;
height: 100vh;
text-align: center;
background: linear-gradient(to left, #24292C, grey, #99958B, #C2BDB3, #EAE7E1, #EAE7E1, #C2BDB3, #99958B, grey, #24292C);
background-size: 200% 100%;
animation: gradientBG 10s ease infinite;

}

@keyframes gradientBG {
0% {
background-position: 0% 50%;
}

50% {
background-position: 100% 50%;
}

100% {
background-position: 0% 50%;
}
}
</style>
<div id="header">
<button alt="Stop Background Motion" id ="stopMotionIcon"onclick="gradientMotion()">
<h1>a</h1>
<script>

function gradientMotion(){
if(document.querySelector("body").style.backgroundSize = "200% 100%"){
document.querySelector("body").style.backgroundSize = "100% 100%"
} else if (document.querySelector("body").style.backgroundSize = "100% 100%"){
document.querySelector("body").style.backgroundSize = "200% 100%"
}
}
</script>
<body>
</body>

最佳答案

真的吗?如果/否则如果!简单点...

const BgSize = [ '200% 100%', '100% 100%']
var indx = 0

document.getElementById('stopMotionIcon').onclick =_=>
{
indx = ++indx %2
document.body.style.backgroundSize = BgSize[indx]
}
body {
font-family: verdana, arial, sans-serif;
font-size: 14px;
margin: 0;
width: 100%;
height: 100vh;
text-align: center;
background: linear-gradient(to left, #24292C, grey, #99958B, #C2BDB3, #EAE7E1, #EAE7E1, #C2BDB3, #99958B, grey, #24292C);
background-size: 200% 100%;
animation: gradientBG 10s ease infinite;
}

@keyframes gradientBG {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
<header>
<button id="stopMotionIcon" >Stop Background Motion</button>
<h1>a</h1>
</header>

关于javascript - 使用 JavaScript 在单击时修改 css BackgroundSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com