onmouseover onmouseout fadeIn fadeOut no jQuery

為{幸葍}努か 提交于 2019-12-13 15:49:05

问题


Im looking for an elegant solution for a fade in and out of an HTML element onmouseover on mouseout without using jQuery (call me old fashioned).

In theory the below js solution should work however I am having problems with it working could someone point me in the right direction or offer an alternative solution??

My Js functions are and the HTML which is inserted is the same as which is on the page...

function fadeIn(element) {

   for (i = 0; i < 100; i++) {
      var value = 0 + i;


      element.style.opacity = value;
      element.style.filter = 'alpha(opacity=' + value + ')';
   }
}

function fadeOut(element) {

   for (i = 0; i < 100; i++) {
      var value = 100 - i;

      element.style.opacity = value;
      element.style.filter = 'alpha(opacity=' + value + ')';
      element.innerHTML = "<div class='container' id='container' onmouseover='fadeOut(this)'><img src='./images/myImage.jpg' onload='fadeIn(this.parent)' /></div>";

   }
}

回答1:


Your fadeIn/Out doesn't work right because you haven't done anything to control the rate of change. That will just execute immediately and show/hide the elements.

Try something like this:

function fadeIn(el) {
   var opac = 0;
   var i = setInterval(function() {
     opac += 10;
     if (opac >= 100) {
       clearInterval(i);
       opac = 100;
     }
     el.style.opacity = opac;
     el.style.filter = 'alpha(opacity=' + opac + ')';

   }, 20);
}

That should fade in over 200ms (20 * 100 / 10). Play with the numbers to adjust the speed.

As for mouseover/out, you can just bind the events like anything else.

Generally, attaching JS events like you have, using HTML attributes, is frowned upon. Usually you'd have a helper like this: https://gist.github.com/955642

You want to write your own method that will check which of the main methods, addEventListener or attachEvent your browser supports.



来源:https://stackoverflow.com/questions/10309197/onmouseover-onmouseout-fadein-fadeout-no-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!