Vanilla Javascript .fadein() .fadeOut() without JQuery [closed]

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

I am developing for IE10+ so i decided not to use JQuery. I write custom javascript function to Select, Fadein, FadeOut etc and it is working fine. but i like to use the Function in JQuery Style (Object.fadeIn(), Object.FadeOut() etc).

Instead of JQuery Selector i use this.

function _(el){     return document.getElementById(el); } 

When i need to select a Dom object i use this.

var myButton = _("button"); 

When i need to fadeIn Or fadeOut any object i use this.

function fade(type, ms, el) {   var isIn = type === 'in',     opacity = isIn ? 0 : 1,     interval = 50,     duration = ms,     gap = interval / duration;    if(isIn) {     el.style.display = 'inline';     el.style.opacity = opacity;   }    function func() {     opacity = isIn ? opacity + gap : opacity - gap;     el.style.opacity = opacity;      if(opacity <= 0) el.style.display = 'none'     if(opacity <= 0 || opacity >= 1) window.clearInterval(fading);   }    var fading = window.setInterval(func, interval);  } 

Here is the specific code to fade my button

fade('out', 500, myButton); 

I like to use like this _( "myButton" ).fadeIn( 100 );

Update: The trick was to use prototype function for "-" to add additional functionality like fadein(), fadeOut() .

回答1:

This will do the trick:

function _(el) {   if (!(this instanceof _)) {     return new _(el);   }   this.el = document.getElementById(el); }  _.prototype.fade = function fade(type, ms) {   var isIn = type === 'in',     opacity = isIn ? 0 : 1,     interval = 50,     duration = ms,     gap = interval / duration,     self = this;    if(isIn) {     self.el.style.display = 'inline';     self.el.style.opacity = opacity;   }    function func() {     opacity = isIn ? opacity + gap : opacity - gap;     self.el.style.opacity = opacity;      if(opacity <= 0) self.el.style.display = 'none'     if(opacity <= 0 || opacity >= 1) window.clearInterval(fading);   }    var fading = window.setInterval(func, interval); }  _('myButton').fade('out', 500); 

From here on out you can extend your _ object with any jQuery-like function.



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