简体   繁体   中英

Problem with setInterval

I have a problem with setInterval on a 'click' event. Im already spawning a hidden div. But I want spawn and fade in synced and only run the fade in ones.

 var anchor = document.getElementById('anchor');
                var hiddenElement = document.getElementById('hiddenElement');
                var bkgFade = document.getElementById('bkgFade');

                anchor.addEventListener('click', spawnImage, false);
                hiddenElement.addEventListener('click', despawnImage, false);
                function spawnImage() {
                     setInterval(function() {
                        document.getElementById('hiddenElement').style.display = 'block';
                        document.getElementById('bkgFade').style.visibility = 'visible';
                         hiddenElement.style.opacity += 1.0;
                    } 1000);


                }

                function despawnImage() {
                    document.getElementById('hiddenElement').style.display = 'none';
                    document.getElementById('bkgFade').style.visibility = 'hidden';
                }

This piece of code makes no sense to me:

function spawnImage() {
     setInterval(function() {
        document.getElementById('hiddenElement').style.display = 'block';
        document.getElementById('bkgFade').style.visibility = 'visible';
        F hiddenElement.style.opacity += 1;
    });
    clearInterval();
}

There are multiple things wrong with it.

  1. You aren't setting a time for setInterval() .
  2. You aren't saving the return value from setInterval() .
  3. You aren't passing anything to clearInterval() . It should be passed the return value from setInterval() . It won't do anything the way you have it.
  4. This line isn't legal javascript: F hiddenElement.style.opacity += 1;
  5. I can't understand why you would setInterval() and then immediately clearInterval()
  6. Adding 1 to the opacity in a timer interval isn't going to accomplish anything. That's just going to make it visible in one giant step.
  7. Manipulating opacity directly won't work in some versions of IE.
  8. You're using document.getElementById('hiddenElement') in one place and hiddenElement in another place. If hiddenElement is valid, use that both places. If not, use document.getElementById('hiddenElement') both places.

If you describe in more detail what you're really trying to accomplish with this code, folks might be able to help you come up with correct code.

I would highly recommend that animation be done with a library like jQuery or YUI as it's way, way easier to use and make it work cross-browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM