首页 > 解决方案 > 使用 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>

标签: javascriptcss

解决方案


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

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>


推荐阅读