Velocity.js升级至2.0.3后出现Cannot read property 'pattern'错误
Hey there, let's figure out why your Velocity animation is throwing that error now. The Cannot read property 'pattern' of undefined error in Velocity 2.x usually pops up when the library hits an unexpected value while parsing your animation properties, or when it can't find the elements you're trying to animate. Here's how to troubleshoot and fix it:
Common Causes & Solutions
1. Your selector isn't matching any elements
First, double-check that $('[id^=home-layer-]') is actually finding elements on the page. If this selector returns an empty jQuery object, Velocity's internal parsing logic can break and throw this error.
Fix:
- Open your browser's dev tools console and run
$('[id^=home-layer-]')directly. If the result has a length of 0, either:- The elements haven't loaded yet when your script runs (wrap your code in a DOM-ready handler):
$(document).ready(function() { const duration = 1000; // Make sure duration is defined $('[id^=home-layer-]').velocity({ transform: 'scale(2)' }, { duration: duration, easing: "ease-out", loop: false }); }); - Or your element IDs don't match the
home-layer-prefix (double-check your HTML for typos).
- The elements haven't loaded yet when your script runs (wrap your code in a DOM-ready handler):
2. The duration variable is undefined or invalid
If duration isn't declared, or has a non-numeric value (like undefined or NaN), Velocity can choke while parsing the animation options.
Fix:
- Verify
durationhas a valid numeric value. Add a console log to check:console.log('Duration value:', duration); // Should be a number like 1000 - If it's undefined, set a default value (e.g.,
const duration = 1000;) or ensure the variable is properly initialized before running the animation.
3. Try Velocity's recommended transform syntax
Velocity 2.x supports both string and object syntax for transforms. Sometimes using the object format avoids parsing issues:
Fix:
Rewrite your animation to use the object-based transform syntax:
$('[id^=home-layer-]').velocity({ transform: { scale: 2 } }, { duration: duration, easing: "ease-out", loop: false });
4. Check jQuery and Velocity compatibility
Velocity 2.x requires jQuery 1.8.0 or later. If you're using an older jQuery version, it might cause unexpected conflicts.
Fix:
Update your jQuery to a version that's compatible with Velocity 2.x (1.8.0+).
Testing Steps
- Run your selector in the console to confirm elements exist.
- Hardcode
durationto a number (like 1000) to rule out variable issues. - Switch to the object transform syntax and test again.
内容的提问来源于stack exchange,提问作者Pepe

