纯粹是创建我自己的淡出功能



我试图用纯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>

当我阅读你的代码时,我发现你可能想在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>

您正试图将函数作为属性添加到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>

您的代码正试图在一个不存在的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>

最新更新