【问题标题】:Listen for mouse click and keypress events within iframe监听 iframe 中的鼠标点击和按键事件
【发布时间】:2014-10-12 10:33:47
【问题描述】:

我想为嵌入的swipe.to 演示文稿的每张幻灯片添加一些解释。 因此,我试图计算按下 iframe 中的按钮或完成某些击键的次数。目标是确定用户在哪张幻灯片上显示适当的幻灯片说明。

如果用户单击 ID 为 #next 的链接或按空格键或右箭头,则整数应递增。如果用户单击 ID 为 #previous 的链接或按左箭头,则整数应减小。

关于鼠标点击事件,answer 确实帮了我很多。它就像一个魅力。但是,我仍然很难让按键事件正常工作。

这是我得到的:

嵌入代码

<figure class="swipe">
   <iframe src="https://www.swipe.to/embed/0882x" allowfullscreen></iframe>
</figure>
<style>figure.swipe{display:block;position:relative;padding-bottom:56.25%;height:0;overflow:hidden;}figure.swipe iframe{position:absolute;top:0;left:0;width:100%;height:100%;border:none;}</style>

确定幻灯片计数的代码

<script>
        $('body iframe').load(function(){
            var i = 0;
            $('body iframe').contents().find('#next').bind('click',function(e) {
                    i++;
                    alert(i);
            });

            $('body iframe').contents().bind('keypress',function(e) {
                    if(e.keyCode == 32){
                        i++;
                        alert(i);
                    }
            });

            $('body iframe').contents().bind('keypress',function(e) {
                    if(e.keyCode == 39){
                        i++;
                        alert(i);
                    }
            });

            $('body iframe').contents().find('#previous').bind('click',function(e) {
                    i--;
                    alert(i);
            });

            $('body iframe').contents().bind('keypress',function(e) {
                    if(e.keyCode == 37){
                        i--;
                        alert(i);
                    }
            });


        });
</script>

【问题讨论】:

  • 您无法访问不同域上的 iFrame
  • 但为什么它对点击下一个/上一个按钮有效?

标签: javascript jquery html iframe


【解决方案1】:

可以这样:

//left arrow
$(document.getElementById('frame-id').contentWindow.document).keydown(function(e){
                if(e.keyCode == 37){
                    i--;
                };
});

//right arrow and space bar
$(document.getElementById('test').contentWindow.document).keydown(function(e){
                if(e.keyCode == 32 || e.keyCode == 39){
                    i++;
                };
});

这应该嵌入$('body iframe').load(function(){ }

【讨论】:

  • 此解决方案仅在 iframe 内容来自同一域时才有效。
猜你喜欢
  • 2011-09-19
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2020-02-20
相关资源
最近更新 更多