javascript – 当位置:粘性被触发时的事件

前端之家收集整理的这篇文章主要介绍了javascript – 当位置:粘性被触发时的事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用新的位置:sticky( info)来创建类似iOS的内容列表.

它的工作性能比以前的JavaScript替代方案(example)要好得多,但据我所知,触发时没有触发任何事件,这意味着我们不能在页面顶部进行任何操作,与之前的解.

当有位置:sticky的元素点击页面顶部时,我想添加一个类(例如卡住).有没有办法用JavaScript来听这个? jQuery的用法很好.

新职位的演示:粘贴在使用中可以找到here.

解决方法

目前没有本地解决方案.请参阅 Targeting position:sticky elements that are currently in a ‘stuck’ state.但是,我有一个CoffeeScript解决方案,与原始位置:粘性和使用实现粘性行为的聚合物.

将“粘性”类添加到要粘贴的元素中:

  1. .sticky {
  2. position: -webkit-sticky;
  3. position: -moz-sticky;
  4. position: -ms-sticky;
  5. position: -o-sticky;
  6. position: sticky;
  7. top: 0px;
  8. z-index: 1;
  9. }

CoffeeScript监视“粘性”元素位置,并在“粘性”状态下添加“卡住”类:

  1. $-> new StickyMonitor
  2.  
  3. class StickyMonitor
  4.  
  5. SCROLL_ACTION_DELAY: 50
  6.  
  7. constructor: ->
  8. $(window).scroll @scroll_handler if $('.sticky').length > 0
  9.  
  10. scroll_handler: =>
  11. @scroll_timer ||= setTimeout(@scroll_handler_throttled,@SCROLL_ACTION_DELAY)
  12.  
  13. scroll_handler_throttled: =>
  14. @scroll_timer = null
  15. @toggle_stuck_state_for_sticky_elements()
  16.  
  17. toggle_stuck_state_for_sticky_elements: =>
  18. $('.sticky').each ->
  19. $(this).toggleClass('stuck',this.getBoundingClientRect().top - parseInt($(this).css('top')) <= 1)

注意:此代码仅适用于垂直粘性位置.

猜你在找的JavaScript相关文章