简体   繁体   中英

How can I make sure that my variable does not change inside the setInterval

I want to change the scrollLeft of a div on time,

let's make it simple :

var initialValue = $('#myDiv').scrollLeft();
var x = setInterval(function() {
$('#myDiv').scrollLeft("#some value calculated depending on initialValue")
}, 10)

the problem is the initialValue changes over time, the same problem remains when i put it inside the setInterval. How can I make sure that my initialValue variable does not change inside the setInterval ?

Just use the scrollWidth property directly thus:

Note: if you want to start at a particular scroll point, simply set el.scrollWidth to that starting value

 var el = document.querySelector('#myDiv'); var step = (el.scrollWidth - el.scrollLeft)/10; var x = setInterval(function() { el.scrollLeft += step; if(el.scrollLeft >= el.scrollWidth - el.clientWidth) clearInterval(x); }, 100); 
 #myDiv { border: 1px solid black; width: 250px; margin-bottom: 12px; overflow-x: scroll; } 
 <div id="myDiv"> ABCDEFGHIJKLMOPQRSTUVWXYZABCDEFGHIJKLMOPQRSTUVWXYZ </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM