纯Javascript-创建自己的淡出函数

时间:2018-07-20 14:30:19

标签: javascript

我正在尝试创建与纯JavaScript的jquery .fadeOut()效果类似的函数,但是我的代码遇到了麻烦。错误代码:

  

span [0] .fadeOutEffect不是函数

我的代码:

var span = document.querySelectorAll("span");

function fadeOutEffect() {
  var node = this
  var fadeEffect = setInterval(function() {
    if (!node.style.opacity) {
      node.style.opacity = 1;
    }
    if (node.style.opacity > 0) {
      node.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 50);
}

span[0].fadeOutEffect();
<span>one </span><span>two </span><span>three </span>

3 个答案:

答案 0 :(得分:1)

当我阅读您的代码时,我看到您可能想向HTMLElement原型添加一个功能-不推荐使用,但它看起来像这样:

HTMLElement.prototype.fadeOutEffect = function() {
  var node = this
  var fadeEffect = setInterval(function() {
    if (!node.style.opacity) {
      node.style.opacity = 1;
    }
    if (node.style.opacity > 0) {
      node.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 50);
}

var span = document.querySelectorAll("span");


span[0].fadeOutEffect();
<span>one </span><span>two </span><span>three </span>

一种更干净的方法正在传递跨度:

var fadeOutEffect = function(node) {
  var fadeEffect = setInterval(function() {
    if (!node.style.opacity) {
      node.style.opacity = 1;
    }
    if (node.style.opacity > 0) {
      node.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 50);
}

var span = document.querySelectorAll("span");


fadeOutEffect(span[0]);
<span>one </span><span>two </span><span>three </span>

答案 1 :(得分:0)

您的代码正在尝试在DOM元素上调用一个不存在的函数。尝试将元素作为参数传递给函数。

var span = document.querySelectorAll("span");

function fadeOutEffect(node) {
  var fadeEffect = setInterval(function() {
    if (!node.style.opacity) {
      node.style.opacity = 1;
    }
    if (node.style.opacity > 0) {
      node.style.opacity -= 0.1;
    } else {
      clearInterval(fadeEffect);
    }
  }, 50);
}

fadeOutEffect(span[0]);
<span>one </span><span>two </span><span>three </span>

答案 2 :(得分:0)

您正在尝试将函数作为属性添加到span元素的数组中。您应该将其作为参数传递给您创建的函数。另外,document.querySelectorAll("span");返回一个范围数组,因为HTML文档中可以有多个范围,因此您可以遍历每个范围并将代码应用于它们。

请参见工作示例:

function fadeOutEffect(nodes) {
  nodes.forEach(function(node) { // Loop through each node (each span) in the array of spans
    var fadeEffect = setInterval(function() { // Run your code
      if (!node.style.opacity) {
        node.style.opacity = 1;
      }
      if (node.style.opacity > 0) {
        node.style.opacity -= 0.1;
      } else {
        clearInterval(fadeEffect);
      }
    }, 50);
  });
}

var nodes = document.querySelectorAll("span"); // Nodes is an array of spans
fadeOutEffect(nodes); // Pass the array of spans to your function
<span>Hello world!</span>