如何将这段含jQuery数组处理的代码改写为原生JavaScript?
Convert jQuery Image Crossfade Code to Pure Vanilla JavaScript
Got it, let's break this down and swap out the jQuery bits for plain JavaScript—starting with the exact line you're focused on.
What the Original jQuery Code Does
First, let's recap the key jQuery lines you want to replace:
var imgs = $.makeArray($("#images img")); imgs.reverse();
This does three core things:
- Selects all
<img>elements inside the container with IDimagesusing jQuery's selector - Converts the jQuery collection to a plain JavaScript array (since jQuery objects aren't true arrays)
- Reverses the order of the array
Vanilla JavaScript Replacement
For vanilla JS, we can replicate this logic cleanly with native APIs:
- Use
document.querySelectorAll()to grab the image elements (returns a NodeList, which is array-like) - Convert the NodeList to a real array with either
Array.from()(great for wider browser compatibility) or the spread operator[... ](more concise, modern browsers only) - Call the native
Array.reverse()method (works exactly like the jQuery version)
Full Rewritten Code
Here's the complete vanilla JS version, with zero jQuery dependencies:
// Replace jQuery selection + array conversion with vanilla JS var imgs = Array.from(document.querySelectorAll("#images img")); // Or use spread operator for modern browsers: var imgs = [...document.querySelectorAll("#images img")]; imgs.reverse(); function crossfade() { // TweenMax code stays identical—it works with plain DOM elements TweenMax.to(imgs[0], 1, { autoAlpha: 0, scale: 1 }); TweenMax.to(imgs[1], 1, { autoAlpha: 1, scale: 1.2 }); // Array shift/push logic is native JS, no changes needed imgs.push(imgs.shift()); } var cycle = setInterval(crossfade, 3000);
Quick Notes
- The
TweenMaxcalls don't need tweaks—GSAP (which TweenMax is part of) works flawlessly with plain DOM elements, no jQuery required. - If you need to support Internet Explorer 11, stick with
Array.from()instead of the spread operator, since IE11 doesn't support the spread syntax for NodeLists. - The array manipulation (
push,shift) is already native JavaScript, so that part stays exactly as-is.
内容的提问来源于stack exchange,提问作者dotun seyi
相关产品推荐
相关产品推荐

