我制作一个小的jquery脚本。 当您在页面上滚动并且超过350时。显示一个按钮。 当你回去时,按钮是隐藏的。 这是脚本:
var button = $('a[title*="terug naar boven"]'); $(document).bind('scroll', function(e) { if (window.scrollY > 350) { button.animate ({ opacity: 1 }) } if (window.scrollY < 350) { button.animate ({ opacity: 0 }) } });但问题是。 脚本继承是。 当我滚动。 每次剧本都是火。 我怎样才能解决这个问题? 那是脚本一次火。
I make a small jquery script. When you scroll on the page and your are over 350. Than a button is show. When you going back, the button is hide. This is the script:
var button = $('a[title*="terug naar boven"]'); $(document).bind('scroll', function(e) { if (window.scrollY > 350) { button.animate ({ opacity: 1 }) } if (window.scrollY < 350) { button.animate ({ opacity: 0 }) } });But the problem is. That the script succession is. When i scroll. The script is fire everytime. How can i fix this? That is script is fire one time.
最满意答案
要防止按钮在其处于正确状态(显示或隐藏)时被设置动画,您应该保持该按钮的状态。
您可以使用变量来执行此操作
var buttonState = 0; $(document).bind('scroll', function(e) { if (window.scrollY > 350 && buttonState == 0) { buttonState = 1; button.animate ({ opacity: 1 }) } if (window.scrollY < 350 && buttonState == 1) { buttonState = 0; button.animate ({ opacity: 0 }) } });或者,您也可以使用按钮的不透明度级别作为状态
如果只想运行一次,则可以取消绑定事件的处理程序
$(document).bind('scroll', function(e) { if (window.scrollY > 350) { button.animate ({ opacity: 1 }) } if (window.scrollY < 350) { button.animate ({ opacity: 0 }) } $(document).unbind('scroll'); });To prevent the button from being animated if its already in the right state (either shown or hidden), you should maintain state of the button.
You can use a variable to do this
var buttonState = 0; $(document).bind('scroll', function(e) { if (window.scrollY > 350 && buttonState == 0) { buttonState = 1; button.animate ({ opacity: 1 }) } if (window.scrollY < 350 && buttonState == 1) { buttonState = 0; button.animate ({ opacity: 0 }) } });Alternatively, you can also use the button's opacity level as state
If you want to run this only once, you can unbind handlers for the event
$(document).bind('scroll', function(e) { if (window.scrollY > 350) { button.animate ({ opacity: 1 }) } if (window.scrollY < 350) { button.animate ({ opacity: 0 }) } $(document).unbind('scroll'); });更多推荐
发布评论