监听 iframe 中的鼠标单击和按键事件

Nic*_*ico 3 html javascript iframe jquery

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

如果用户单击带有 id 的链接#next或按空格键或右箭头,则整数应该增加。如果用户单击带有 id 的链接#previous或按左箭头,则整数应该减少。

关于鼠标点击事件这个答案对我帮助很大。它就像一个魅力。然而,我仍然很难让按键事件正常工作。

这就是我所得到的:

嵌入代码

<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>
Run Code Online (Sandbox Code Playgroud)

确定幻灯片计数的代码

<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>
Run Code Online (Sandbox Code Playgroud)

Nic*_*ico 5

可以这样:

//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++;
                };
});
Run Code Online (Sandbox Code Playgroud)

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

  • 仅当 iframe 内容来自同一域时,此解决方案才有效。 (5认同)