没有JQuery的Vanilla Javascript .fadein()。fadeOut() [英] Vanilla Javascript .fadein() .fadeOut() without JQuery

查看:83
本文介绍了没有JQuery的Vanilla Javascript .fadein()。fadeOut()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为IE10 +开发,所以我决定不使用JQuery。我为Select,Fadein,FadeOut等编写自定义javascript函数,它工作正常。
但我喜欢在JQuery样式中使用函数(Object.fadeIn(),Object.FadeOut()等)。

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).

而不是我使用的JQuery Selector这个。

Instead of JQuery Selector i use this.

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

当我需要选择Dom对象时,我会使用它。

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

var myButton = _("button");

当我需要fadeIn或fadeOut我使用的任何对象时。

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);

我喜欢这样使用 _(myButton)。fadeIn( 100);


更新:诀窍是使用原型函数 - 添加额外的
功能,如fadein(),fadeOut()。

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


推荐答案

这样就可以了:

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);

从现在开始,你可以扩展 _ 具有任何类似jQuery的函数的对象。

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

这篇关于没有JQuery的Vanilla Javascript .fadein()。fadeOut()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆