如何逐个淡入class为data的元素?调用fadeIn方法报错求助
.data Elements Hey there! I see you're trying to get your .data elements to fade in one after another, but hitting errors when using index-based calls. Let's break down the problem and fix it step by step.
Why Your Current Code Fails
When you use $(".data")[0], you're accessing the raw DOM element from the jQuery collection, not a jQuery object. Methods like fadeIn() and delay() are jQuery-specific—they won't work on native DOM nodes. That's exactly why you're seeing errors!
Step 1: Set Initial Hidden State
First, your .data elements need to be hidden by default so fadeIn() has something to animate. You can do this either in CSS:
.data { width: 74%; background: red; height: 20px; position: absolute; right: 13%; display: none; /* Add this line to hide elements initially */ display: flex; text-align: center; }
Or with jQuery (if you don't want to modify your CSS):
$(".data").hide();
Step 2: Implement Sequential Fade-In
Here are two reliable ways to make the elements fade in one after another:
Method 1: Target Elements Individually (For Small Fixed Sets)
Use jQuery's .eq() method to get a jQuery object for each index, then chain delay() and fadeIn():
// Hide all elements first $(".data").hide(); // Fade in each element with staggered delays $(".data").eq(0).fadeIn(2000); $(".data").eq(1).delay(2000).fadeIn(2000); $(".data").eq(2).delay(4000).fadeIn(2000); $(".data").eq(3).delay(6000).fadeIn(2000);
Method 2: Dynamic Loop (Best for Variable Number of Elements)
Use .each() to loop through all .data elements, and use their index to calculate the delay dynamically—this works even if you add/remove elements later:
$(".data").hide().each(function(index) { // Delay increases by 2000ms for each subsequent element $(this).delay(index * 2000).fadeIn(2000); });
Quick Breakdown of the Fix
.eq(index)returns a proper jQuery object (not a raw DOM node), so you can safely call jQuery methods on it.delay()adds a timed pause before the animation runs—using the element's index lets us stagger the timing perfectly.fadeIn(2000)animates the element from hidden to visible over 2 seconds.
内容的提问来源于stack exchange,提问作者Rnayak

