JavaScript scroll to element on binded keydown events in jQuery

僤鯓⒐⒋嵵緔 提交于 2019-12-11 09:57:28

问题


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!


回答1:


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;


来源:https://stackoverflow.com/questions/12993914/javascript-scroll-to-element-on-binded-keydown-events-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!