javascript - 使用 JavaScript 修改 css BackgroundSize 点击
问题描述
我正在使用 css 动画制作动画背景。我可以在单击按钮时将其关闭,但是对于第二次单击不起作用。我知道这是可能的,因为我在控制台中输入了该功能并且它起作用了。
我也已经尝试过 switch 语句和条件语句。
我不想重新加载页面,而是使用相同的按钮再次进行动作。
<!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>
推荐阅读
- python - DataFrame - 带标准的逐行算术
- javascript - Search key and return value in nested object
- reactjs - 类未应用于输入元素 reactjs
- cucumber - How to validate a REST Assured request across multiple java methods?
- c++ - 在浅拷贝上调用删除不会爆炸
- javascript - 谷歌翻译中不显示文本区域建议框中的 Onkeypress
- angular - 如何更新子模型而不重置整个视图?
- azure - Azure AD 的 saml 响应中缺少自定义声明
- reactjs - 将日期和时间合并到一个时刻对象中以与今天进行比较
- sql - 如何使用这个奇怪的 .sql 文件?