滚动事件未在iframe中的body元素中注册

时间:2016-07-27 11:16:46

标签: javascript jquery html css iframe

firefox 中存在一个奇怪的问题,在iframe正文中滚动不会冒泡到父文档。因此,当您完成在iframe内部滚动时,它会卡住并且不会滚动父文档 欢迎使用此问题的任何解决方法。

我的方法是在滚动iframe文档时获取滚动事件,以便我可以手动滚动父文档。但是当iframe文档完全滚动到顶部或底部时,我没有得到滚动事件。
小提琴:https://jsfiddle.net/tdu9197g/

由于跨源策略,它无法在stackoverflow片段中使用。请试试firefox中的小提琴。

$(function(){
  $($('iframe')[0].contentDocument).find('body').css('height',200);
  $($('iframe')[0].contentDocument).find('body').on('click',function(){
     $('iframe')[0].contentDocument.designMode='on';
  })
  $($('iframe')[0].contentDocument).find('body').on('blur',function(){
    console.log('blur called');
  });
  $('body').on('click',function(){
     $('iframe')[0].contentDocument.designMode='off';
  });
  $($('iframe')[0].contentDocument).find('body').on('scroll',function(){
     console.log('scroll');
  })
  $($('iframe')[0].contentDocument).find('body').on('mouseover',function(){
   console.log('scroll');
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




<div>
<iframe>
  
</iframe>
</div>

1 个答案:

答案 0 :(得分:1)

请勿附加body iframe的{​​{1}}元素。

将事件处理程序附加到contentDocument本身:

contentDocument

这会注册滚动事件处理程序,控制台会显示$($('iframe')[0].contentDocument).on('scroll',function(){ console.log('scroll'); }) 语句的结果。