我正在尝试创建一个与 jquery .fadeOut()
类似的函数在纯 JavaScript 中有效,但我的代码遇到了问题。错误代码:
span[0].fadeOutEffect is not a function
我的代码:
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 原型(prototype)添加一个函数 - 不建议这样做,但它看起来像这样:
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>
关于javascript - 纯 javascript - 创建我自己的淡出功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51444819/