I am really squeezing my head to make the simple fade in and fade out of the background image work only with javascript without JQuery and CSS3. I know how easy is to call a fadeIn() and fadeOut() in Jquery. Unfortunately in my project I am working, they don't support Jquery. I want to support the animation from IE6 for your info.
On click of the links the corresponding background of the div to be faded in and out from the previously existing background. I am trying to make it work based on setinterval but could not do it.
function handleClick(evt){var element = document.getElementsByClassName(evt.target.id); fade(element);}function fade(element){var op =1;// initial opacityvar timer = setInterval(function(){if(op <=0.1){ clearInterval(timer); element.style.display ='none';} element.style.opacity = op; element.style.filter ='alpha(opacity='+ op *100+")"; op -= op *0.1;},50);}
Here are my full implementations of fadeIn and fadeOut for cross-browser support (including IE6) which does not require jQuery or any other 3rd-party JS library:
As others have said, you need to fix your handleClick to properly select a single element, then pass that element to the fade function (which I named fadeOut for clarity). The default time for a jQuery fade is 400ms, so if you want to mimic that, your call might look like this:
function handleClick( evt ){ fadeOut( document.getElementById(evt.target.id),400);}
回答3:
If you do not care about IE7 - IE9, you can use very useful CSS3 transitions, something like this:
Side note: Using console.log() and some type of developer console (like the one included in Chrome) can work wonders for debugging.
回答5:
You should really do this via CSS3 since all modern browsers support it, and for older browsers fallback to just using show/hide. Do this by adding a "fadeOut" class or removing it via JavaScript. CSS3 (transitions) handle everything else, including hiding and showing it for older browsers.
Remember: As much as possible, do things in CSS before doing them in JavaScript. Not only is it cleaner and easier to maintain but CSS3 animations render smoother as it often hardnesses the GPU (video card) and not just the CPU. This is especially important on mobile devices but is the standard, modern way for doing it in any device.
I made a JS fiddle for you here It's semicomplete but shows off how you should go about making your fadeout/fadein. This is tested in Chrome on a Mac. Not sure about FF nor IE unfortunately.
Also as several pointed out, when getting stuff by any function that ends with s you can be 100% sure that it gives you an array with elements and thus you have to refer to the element you want as such. In your case its element[0].
Hope I help you further a little ways! :) Good luck!