iMacros脚本优化:基于{{LOOP}}值实现页面滚动的高效方案问询
Hey there! Let's clean up that repetitive code and fix a subtle issue in your current approach first: each SET scrolla line overwrites the previous one, so only the last condition (checking for 60) actually takes effect. That's not what you want when targeting values up to 20000+.
Here are two optimized solutions tailored to your iMacros for Chrome PE v10.1.1 environment:
Solution 1: Math-Based Check (Most Efficient)
This approach uses basic arithmetic to detect when {{!LOOP}} is a multiple of 20 (your target values: 20, 40, 60... up to 20000+), avoiding the need for endless conditional checks:
SET !LOOP 20 SET scrolla EVAL("var loopNum = parseInt('{{!LOOP}}'); var scrollAmount = (loopNum % 20 === 0 && loopNum >= 20) ? 5000 : 500; 'javascript:window.scrollBy(0,' + scrollAmount + ')';") ' URL GOTO={{scrolla}} PROMPT {{scrolla}}
Breakdown:
parseInt('{{!LOOP}}'): Converts the loop value from a string to a number for mathematical operations.loopNum % 20 === 0: Checks if the loop number is a multiple of 20 (covers all your target values automatically, no matter how high you go).loopNum >= 20: Ensures we only apply the large scroll to values starting from 20 (remove this if you want any multiple of 20 to trigger it).- Ternary operator (
? :): SetsscrollAmountto 5000 when the condition is met, 500 otherwise. - Dynamic scroll string: Builds the JavaScript command without hardcoding values, keeping the code clean.
Solution 2: CSV-Driven Flexibility (Your Initial Idea)
If you need more control later (e.g., adding non-sequential target values), using a CSV file is a solid option. Here's how to implement it properly:
Create a CSV file (e.g.,
scroll_triggers.csv) with one column listing your target loop values:20 40 60 ... 20000Use this iMacros code to reference the CSV:
SET !DATASOURCE scroll_triggers.csv SET !DATASOURCE_COLUMNS 1 SET !LOOP 1 ' Map loop iteration to CSV row (adjust if your loop counter doesn't start at 1) SET targetValue {{!COL1}} SET scrolla EVAL("var loopNum = parseInt('{{!LOOP}}') * 20; var target = parseInt('{{targetValue}}'); var scrollAmount = (loopNum === target) ? 5000 : 500; 'javascript:window.scrollBy(0,' + scrollAmount + ')';") ' URL GOTO={{scrolla}} PROMPT {{scrolla}}
Note:
Adjust the loopNum = parseInt('{{!LOOP}}') * 20 line if your loop counter doesn't align 1:1 with the CSV rows (e.g., if !LOOP starts at 20 instead of 1, remove the *20 part).
The math-based solution is best for your current needs—it's concise, doesn't require external files, and scales effortlessly even for loop values up to 20000+. Let me know if you need help adapting this to your exact workflow!
内容的提问来源于stack exchange,提问作者Ionut Bejinariu

