JavaScript滚动到jQuery中绑定的keydown事件的元素 [英] JavaScript scroll to element on binded keydown events in jQuery

查看:128
本文介绍了JavaScript滚动到jQuery中绑定的keydown事件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试滚动到keydown事件中的2个不同元素,第一次按下第一个元素,第二次按下第二个元素,并在每次按下两次(或点击)后重复该事件。我创建了一个JSFiddle演示,链接如下。



FIDDLE

正如您所看到的,它不会滚动到第二次按下(或点击)时的底部元素。我唯一能想到的是除了.offset()。top以外的其他事情。但是,如果你的一些JS大师看我的代码,你可能会看到错误或可能是另一种解决方案,以达到预期的效果。提前致谢!

  .offset()。top ??? 

主要错误已解决,但新的错误显示。是否有方法将命中变量重置为零如果用户点击向上箭头??



没有更多的错误!您可以随意使用此脚本!

偏移量


获取当前坐标匹配元素集合中的第一个元素,相对于文档。


这里的问题是当您为 #wrap 元素设置动画时,其偏移量会更改
最简单的解决方案是事先获得它的位置,请参阅我编辑的JSfiddle 。添加以下两行代码,并根据spot1 / spot2执行动画。开关盒可以正常工作。

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


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;

这篇关于JavaScript滚动到jQuery中绑定的keydown事件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆