简体   繁体   中英

JavaScript scroll to element on binded keydown events in jQuery

I am trying to scroll to 2 different elements in a keydown event, 1st element on the first press, 2nd element on second press, and repeat the event after every 2 presses (or hits). I created a JSFiddle demo, linked below.

FIDDLE

As you can see, it will not scroll to the bottom element on the second press (or hit). The only thing I can think of is using something else besides ".offset().top" for the second event. But if some of you JS gurus look at my code you may see the bug or perhaps another solution for the desired effect. Thanks in advance!

.offset().top ???

MAIN BUG SOLVED, but new bug revealed.. Is there a way to reset the hit variable to ZERO if the user clicks the UP arrow??

NO MORE BUGS! FEEL FREE TO USE THIS SCRIPT ALL YOU WANT!

See the definitions of offset

Get the current coordinates of the first element in the set of matched elements, relative to the document.

the problem here is when you animated the #wrap element, its offset changes the easiest solution is to get its position beforehand, see my edited JSfiddle . Add the following two lines of code, and do the animation according to spot1/spot2. The switch case executes fine.

var spot1 = $("#scrollToHere2").position().top;
var spot2 = $("#scrollToHere").position().top;

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