Listen for mouse click and keypress events within

2019-02-19 17:32发布

I would like to add some explanations to each slide of an embedded swipe.to presentation. Therefore I am trying to count the times a button within the iframe is pressed or certain keystrokes are done. The goal is to determine on which slide the user is in order to display the appropriate slide explanation.

If the user clicks on the link with id #next or presses space bar or right arrow an integer should increment. If the user clicks on the link with id #previous or presses left arrow the integer should decrease.

Regarding the mouse click events this answer did help me a lot. It works like a charm. However I am still having a hard time getting the keypress events to work.

This is what I have got:

embedding code

<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>

code for determining slide count

<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>

1条回答
Lonely孤独者°
2楼-- · 2019-02-19 17:57

It is possible this way:

//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++;
                };
});

This should be embedded within $('body iframe').load(function(){ }

查看更多
登录 后发表回答