为什么一个 IF 语句会导致我的函数重复执行?

huangapple go评论91阅读模式
英文:

Why does en IF statement make my function repeat?

问题

以下是代码部分的翻译:

<!DOCTYPE html>
<html lang="sv">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sensor Assignment</title>
    <meta name="description" content="Demo av en animerad bil som kan manipuleras med mobiltelefoners gyro-sensor">
    <meta name="author" content="b22thohe">
    <script src="https://raw.githack.com/HGustavs/Shaker.js/master/shaker.js"></script>
    <script>
      var toggle = 0;

      function changeBackground(edata) {
        /* Debug output */
        document.getElementById("printout").innerHTML += "Detected SHAKES: " + edata.shakes + "<BR>"; /* print out # shakes registered */

        if (toggle == 0) {
          document.getElementById("svg").style.background = 'linear-gradient(0deg, rgba(150,150,150,1) 43%, rgba(0,187,255,1) 62%, rgba(0,63,255,1) 93%)'; // Ändrar bakgrunden i viewboxen
          document.getElementById("sun").transform.fill('yellow'); // Ändrar bakgrunden på solen
          toggle = 1;
        } else if (toggle == 1) {
          document.getElementById("svg").style.background = 'linear-gradient(0deg, rgba(23,16,198,1) 7%, rgba(30,10,138,1) 39%, rgba(56,56,59,1) 100%)'; // Ändrar bakgrunden i viewboxen
          document.getElementById("sun").transform.fill('lightgrey'); // Ändrar bakgrunden på solen
          toggle = 0;
        }
      };

      function initShake() {
        shaker.on("shake", function(edata) {
          changeBackground(edata);
        });
      }
    </script>
    <style>
      /* Skapar en gradient som bakgrund och centrerar elementet */
      svg {
        display: block;
        margin: auto;
        background: linear-gradient(0deg, rgba(150, 150, 150, 1) 43%, rgba(0, 187, 255, 1) 62%, rgba(0, 63, 255, 1) 93%);
      }

      /* ... (其他CSS样式) ... */
    </style>
  </head>
  <body id="content" onload="initShake();">
    <svg id="svg" width="100%" viewbox="0 0 900 300" style="border:1px solid black;">
      <!-- ... (其他SVG元素) ... -->
      <pre id="printout">Shaker Events Printout<br></pre>
    </svg>
  </body>
</html>

这是你的HTML和JavaScript代码的翻译。如需帮助或有其他问题,请随时提出。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;sv&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;title&gt;Sensor Assignment&lt;/title&gt;
&lt;meta name=&quot;description&quot; content=&quot;Demo av en animerad bil som kan manipuleras med mobiltelefoners gyro-sensor&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;b22thohe&quot;&gt;
&lt;script src=&quot;https://raw.githack.com/HGustavs/Shaker.js/master/shaker.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
var toggle = 0;
function changeBackground(edata) {
/* Debug output */
document.getElementById(&quot;printout&quot;).innerHTML += &quot;Detected SHAKES: &quot; + edata.shakes + &quot;&lt;BR&gt;&quot;; /* print out # shakes registered */
if (toggle == 0) {
document.getElementById(&quot;svg&quot;).style.background = &#39;linear-gradient(0deg, rgba(150,150,150,1) 43%, rgba(0,187,255,1) 62%, rgba(0,63,255,1) 93%)&#39;; // &#196;ndrar bakgrunden i viewboxen
document.getElementById(&quot;sun&quot;).transform.fill(&#39;yellow&#39;); // &#196;ndrar bakgrunden p&#229; solen   
toggle = 1;
} else if (toggle == 1) {
document.getElementById(&quot;svg&quot;).style.background = &#39;linear-gradient(0deg, rgba(23,16,198,1) 7%, rgba(30,10,138,1) 39%, rgba(56,56,59,1) 100%)&#39;; // &#196;ndrar bakgrunden i viewboxen
document.getElementById(&quot;sun&quot;).transform.fill(&#39;lightgrey&#39;); // &#196;ndrar bakgrunden p&#229; solen
toggle = 0;
}
};
function initShake() {
shaker.on(&quot;shake&quot;, function(edata) {
changeBackground(edata);
});
}
&lt;/script&gt;
&lt;style&gt;
/* Skapar en gradient som bakgrund och centrerar elementet */
svg {
display: block;
margin: auto;
background: linear-gradient(0deg, rgba(150, 150, 150, 1) 43%, rgba(0, 187, 255, 1) 62%, rgba(0, 63, 255, 1) 93%);
}
/* flyttar ut alla SVG-objekt till startposition */
#grp-body {
transform: translate(275px, 235px);
}
#grp-cockpit {
transform: translate(237.5px, 210px);
}
#grp-back-tire {
transform: translate(187.5px, 260px);
}
#grp-front-tire {
transform: translate(362.5px, 260px);
}
#grp-back-hubcap {
transform: translate(187.5px, 260px);
}
#grp-front-hubcap {
transform: translate(362.5px, 260px);
}
#grp-back-wing {
transform: translate(137.5px, 197.5px);
}
#grp-front-wing {
transform: translate(418.75px, 203.75px);
}
#grp-smoke {
transform: translate(75px, 205px);
transition: opacity 9s;
}
#grp-exhaust {
transform: translate(112.5px, 247.5px)
}
#grp-exhaust-flame {
transform: translate(86px, 246px);
}
/* Animerar r&#246;kpuffen */
@keyframes smoke {
0% {
transform: translate(75px, 205px) scale(1);
opacity: 1;
}
33.3% {
transform: translate(3px, 93px) scale(0.3);
opacity: 0;
}
66.6% {
transform: translate(-69px, -19px) scale(0.2);
}
75% {
transform: translate(-107.5px, -82.5px) scale(0.1);
}
100% {
transform: translate(-146px, -146px) scale(0);
}
}
#grp-smoke {
animation-name: smoke;
animation-duration: 12000ms;
animation-iteration-count: 1;
animation-timing-function: linear;
animation-fill-mode: forwards;
animation-play-state: paused;
opacity: 0;
}
/* Animerar bilens r&#246;relse */
@keyframes drive {
0% {
transform: translateX(-460px);
}
100% {
transform: translateX(1260px);
}
}
#grp-entire-vehicle {
animation-name: drive;
animation-duration: 9000ms;
animation-iteration-count: 1;
animation-timing-function: linear;
animation-play-state: paused;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body id=&quot;content&quot; onload=&quot;initShake();&quot;&gt;
&lt;!-- Skapar en rityta --&gt;
&lt;svg id=&quot;svg&quot; width=&quot;100%&quot; viewbox=&quot;0 0 900 300&quot; style=&quot;border:1px solid black;&quot;&gt;
&lt;defs&gt;
&lt;!-- Skapar gradient f&#246;r d&#228;cken --&gt;
&lt;radialGradient id=&quot;tire-gradient&quot;&gt;
&lt;stop offset=&quot;50%&quot; stop-color=&quot;#6f6e6e&quot; /&gt;
&lt;stop offset=&quot;75%&quot; stop-color=&quot;#000000&quot; /&gt;
&lt;stop offset=&quot;100%&quot; stop-color=&quot;#6f6e6e&quot; /&gt;
&lt;/radialGradient&gt;
&lt;!-- F&#246;rbereder animerad bild f&#246;r bakgrund till navkapslarna --&gt;
&lt;pattern id=&quot;hubcap-img&quot; x=&quot;0&quot; y=&quot;0&quot; height=&quot;15&quot; width=&quot;15&quot;&gt;
&lt;image x=&quot;0&quot; y=&quot;0&quot; width=&quot;15&quot; height=&quot;15&quot; xlink:href=&quot;./img/hubcap.png&quot;&gt;&lt;/image&gt;
&lt;animateTransform id=&quot;hubcapAnim&quot; attributeType=&quot;xml&quot; attributeName=&quot;patternTransform&quot; type=&quot;rotate&quot; from=&quot;0&quot; to=&quot;360&quot; begin=&quot;0&quot; dur=&quot;9s&quot; repeatCount=&quot;indefinite&quot; /&gt;
&lt;/pattern&gt;
&lt;/defs&gt;
&lt;!-- Ritar ut bilkroppen --&gt;
&lt;g id=&quot;grp-entire-vehicle&quot;&gt;
&lt;!-- F&#214;RARHYTT --&gt;
&lt;g id=&quot;grp-cockpit&quot;&gt;
&lt;path id=&quot;cockpit&quot; d=&quot;M 0 0 A 25 18.75 0 0 1 100 0&quot; fill=&quot;lightblue&quot; stroke=&quot;blue&quot; stroke-width=&quot;1&quot; stroke-miterlimit=&quot;5&quot; /&gt;
&lt;/g&gt;
&lt;!-- D&#196;CK --&gt;
&lt;g id=&quot;grp-back-tire&quot;&gt;
&lt;circle id=&quot;back-tire&quot; stroke-miterlimit=&quot;5&quot; cx=&quot;0&quot; cy=&quot;0&quot; r=&quot;15&quot; fill=&quot;url(#tire-gradient)&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/circle&gt;
&lt;/g&gt;
&lt;g id=&quot;grp-front-tire&quot;&gt;
&lt;circle id=&quot;front-tire&quot; stroke-miterlimit=&quot;5&quot; cx=&quot;0&quot; cy=&quot;0&quot; r=&quot;15&quot; fill=&quot;url(#tire-gradient)&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/circle&gt;
&lt;/g&gt;
&lt;!-- NAVKAPSLAR --&gt;
&lt;g id=&quot;grp-back-hubcap&quot;&gt;
&lt;circle id=&quot;back-hubcap&quot; stroke-miterlimit=&quot;5&quot; cx=&quot;0&quot; cy=&quot;0&quot; r=&quot;7.5&quot; fill=&quot;url(#hubcap-img)&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/circle&gt;
&lt;/g&gt;
&lt;g id=&quot;grp-front-hubcap&quot;&gt;
&lt;circle id=&quot;front-hubcap&quot; stroke-miterlimit=&quot;5&quot; cx=&quot;0&quot; cy=&quot;0&quot; r=&quot;7.5&quot; fill=&quot;url(#hubcap-img)&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/circle&gt;
&lt;/g&gt;
&lt;!-- KAROSS --&gt;
&lt;g id=&quot;grp-body&quot;&gt;
&lt;rect id=&quot;main-body&quot; x=&quot;-150&quot; y=&quot;-25&quot; width=&quot;300&quot; height=&quot;50&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot; fill=&quot;lightblue&quot;&gt;&lt;/rect&gt;
&lt;/g&gt;
&lt;!-- KAROSS-VINGAR --&gt;
&lt;g id=&quot;grp-back-wing&quot;&gt;
&lt;polygon id=&quot;back-wing&quot; stroke-miterlimit=&quot;5&quot; points=&quot;-12.5,12.5 12.5,12.5 -12.5,-12.5 -12.5,12.5&quot; fill=&quot;lightblue&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/polygon&gt;
&lt;/g&gt;
&lt;g id=&quot;grp-front-wing&quot;&gt;
&lt;polygon id=&quot;front-wing&quot; stroke-miterlimit=&quot;5&quot; points=&quot;6.25,6.25 -6.25,6.25 6.25,-6.25 6.25,6.25&quot; fill=&quot;lightblue&quot; stroke=&quot;blue&quot; stroke-width=&quot;2&quot;&gt;&lt;/polygon&gt;
&lt;/g&gt;
&lt;!-- R&#214;KPUFF --&gt;
&lt;g id=&quot;grp-smoke&quot;&gt;
&lt;circle cx=&quot;9.162&quot; cy=&quot;8.185&quot; r=&quot;25&quot; fill=&quot;rgb(79,77,76,1)&quot; /&gt;
&lt;circle cx=&quot;-5.838&quot; cy=&quot;3.185&quot; r=&quot;25&quot; fill=&quot;rgb(79,77,76,1)&quot; /&gt;
&lt;circle cx=&quot;-15.838&quot; cy=&quot;11.815&quot; r=&quot;21&quot; fill=&quot;rgb(79,77,76,1)&quot; /&gt;
&lt;/g&gt;
&lt;!-- AVGASR&#214;R --&gt;
&lt;g id=&quot;grp-exhaust&quot;&gt;
&lt;polygon id=&quot;exhaust&quot; stroke-miterlimit=&quot;5&quot; points=&quot;-12.5,-9.375 -12.5,9.375 -3.125,6.25 3.125,3.125 12.5,3.125 12.5,-3.125 3.125,-3.125 -3.125,-6.25 -12.5,-9.375&quot; fill=&quot;lightgray&quot; stroke=&quot;black&quot; stroke-width=&quot;0.5&quot;&gt;&lt;/polygon&gt;
&lt;/g&gt;
&lt;!-- AVGAS-FLAMMOR --&gt;
&lt;g id=&quot;grp-exhaust-flame&quot;&gt;
&lt;polygon id=&quot;exhaust-flame&quot; stroke-miterlimit=&quot;5&quot; points=&quot;-25,-23.4375 -12.5,-17.25 -3.125,-11 6.25,-4.75 12.5,-4.75 12.5,7.75 6.25,7.75 -3.125,14 -9.375,20.25 -15.625,23.375 -12.5,17.125 -6.25,7.75 -12.5,10.875 -18.75,14 -31.25,17.125 -25,7.75 -12.5,-1.625 -25,-7.875 -37.5,-14.125 -31.25,-17.25 -12.5,-7.875 -18.75,-17.25 -25,-23.5&quot; fill=&quot;yellow&quot; stroke=&quot;red&quot; stroke-width=&quot;2&quot;&gt;&lt;/polygon&gt;
&lt;/g&gt;
&lt;/g&gt;
&lt;!-- SOL --&gt;
&lt;g id=&quot;sun&quot;&gt;
&lt;circle cx=&quot;500&quot; cy=&quot;50&quot; r=&quot;50&quot; fill=&quot;yellow&quot; /&gt;
&lt;/g&gt;
&lt;!-- Start-knapp --&gt;
&lt;g id=&quot;grp-start-button&quot; onClick=&quot;startAnimation()&quot;&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;rect x=&quot;30&quot; y=&quot;30&quot; width=&quot;100&quot; height=&quot;50&quot; stroke=&quot;black&quot; fill=&quot;green&quot; stroke-width=&quot;3&quot; /&gt;
&lt;text x=&quot;53&quot; y=&quot;63&quot; font-family=&quot;helvetica neue&quot; font-size=&quot;25&quot; fill=&quot;yellow&quot;&gt;Start&lt;/text&gt;
&lt;/a&gt;
&lt;/g&gt;
&lt;g id=&quot;grp-stop-button&quot; onClick=&quot;stopAnimation()&quot;&gt;
&lt;!-- Stopp-knapp --&gt;
&lt;a href=&quot;#&quot;&gt;
&lt;rect x=&quot;140&quot; y=&quot;30&quot; width=&quot;100&quot; height=&quot;50&quot; stroke=&quot;black&quot; fill=&quot;red&quot; stroke-width=&quot;3&quot; /&gt;
&lt;text x=&quot;163&quot; y=&quot;63&quot; font-family=&quot;helvetica neue&quot; font-size=&quot;25&quot; fill=&quot;yellow&quot;&gt;Stop&lt;/text&gt;
&lt;/a&gt;
&lt;/g&gt;
&lt;/svg&gt;
&lt;pre id=&quot;printout&quot;&gt;Shaker Events Printout&lt;br&gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

I've been banging my head against a wall for awhile now so I'm not even sure what I'm doing anymore. The basis is this: I'm using a javascript library to identify when the user "shakes" the phone.

The initShake() function is called on body load. From there I call changeBackground function that outputs the number of shakes registered. This all works fine until I put an IF/ELSE IF statement inside the changeBackground statement, because then the number of shakes output starts repeating seemingly infinitely. And I can't wrap my head around why?

I would like to know why this happens, and of course good ways to remedy this. Is it because of faulty IF statements or something else? Is it because of faulty IF statements or something else?

This is my HTML with the body onload call and element for outputting number of shakes:

&lt;body id=&quot;content&quot; onload=&quot;initShake();&quot;&gt;
&lt;pre id=&quot;printout&quot;&gt;Shaker Events Printout&lt;br&gt;&lt;/pre&gt;
&lt;/body&gt;

This is the initShake() function:

function initShake() {
shaker.on(&quot;shake&quot;,function(edata){
changeBackground(edata);
});
}

And this is the changeBackground function:

function changeBackground(edata) {
/* Debug output */
document.getElementById(&quot;printout&quot;).innerHTML+=&quot;Detected SHAKES: &quot;+edata.shakes+&quot;&lt;BR&gt;&quot;; /* print out # shakes registered */
};

And here's where I load the shaker script:

&lt;script src=&quot;https://raw.githack.com/HGustavs/Shaker.js/master/shaker.js&quot;&gt;&lt;/script&gt;

This is the IF/ELSE IF statement that I put inside the changeBackground function:

if (toggle == 0) {
document.getElementById(&quot;svg&quot;).style.background = &#39;linear-gradient(0deg, rgba(150,150,150,1) 43%, rgba(0,187,255,1) 62%, rgba(0,63,255,1) 93%)&#39;; // &#196;ndrar bakgrunden i viewboxen
document.getElementById(&quot;sun&quot;).transform.fill(&#39;yellow&#39;); // &#196;ndrar bakgrunden p&#229; solen   
toggle = 1;
} else if (toggle == 1) {
document.getElementById(&quot;svg&quot;).style.background = &#39;linear-gradient(0deg, rgba(23,16,198,1) 7%, rgba(30,10,138,1) 39%, rgba(56,56,59,1) 100%)&#39;; // &#196;ndrar bakgrunden i viewboxen
document.getElementById(&quot;sun&quot;).transform.fill(&#39;lightgrey&#39;); // &#196;ndrar bakgrunden p&#229; solen
}

答案1

得分: 1

I don't know why this works exactly, but could you try changing:

document.getElementById("sun").transform.fill('yellow');

to

document.getElementById("sun").querySelector("circle").style.fill = 'yellow';

(and do the same for the lightgrey version).

For anyone who wants to try this in the browser here's a hacky bit of code to do the shaking:

for(let i = 0; i < 200; i++) {
	setTimeout(() => {
	  let event = new DeviceMotionEvent('devicemotion', {accelerationIncludingGravity:{ x: 50 * (i % 2 === 0 ? -1 : 1), y: 0, z: 0 }});

	  window.dispatchEvent(event);
	}, i * 100 + (i % 2 === 0 ? 50 : 0));
}
英文:

I don't know why this works exactly, but could you try changing:

document.getElementById(&quot;sun&quot;).transform.fill(&#39;yellow&#39;);

to

document.getElementById(&quot;sun&quot;).querySelector(&quot;circle&quot;).style.fill = &#39;yellow&#39;;

(and do the same for the lightgrey version).

For anyone who wants to try this in the browser here's a hacky bit of code to do the shaking:

for(let i = 0; i &lt; 200; i++) {
setTimeout(() =&gt; {
let event = new DeviceMotionEvent(&#39;devicemotion&#39;, {accelerationIncludingGravity:{ x: 50 * (i % 2 === 0 ? -1 : 1), y: 0, z: 0 }});
window.dispatchEvent(event);
}, i * 100 + (i % 2 === 0 ? 50 : 0));
}

huangapple
  • 本文由 发表于 2023年3月4日 01:38:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定