Click handler on <video> conflicts with Firefox's native behaviour

后端 未结 2 1051
北荒
北荒 2021-01-19 17:00

I\'ve added a video to my site using the default HTML5 video player. The code is like this:

2条回答
  •  一个人的身影
    2021-01-19 17:50

    You need to prevent the default behaviour of the click event, in much the same way that you would prevent the default behaviour of a form submit if you were handling it yourself with JavaScript.

    Event.preventDefault is the tool for the job.

    Just do

    video.addEventListener('click', function (event) {
        event.preventDefault(); // Prevent the default behaviour in Firefox
    
        // Then toggle the video ourselves
        if (this.paused) {
            this.play();
        }
        else {
            this.pause();
        }
    });
    

    Here's a Fiddle that works both in Chrome (which has no built-in click-to-toggle behaviour on videos) and in Firefox (which, at least in recent versions, does): http://jsfiddle.net/LjLgkk71/

    As an aside, as a general rule you should forget browser sniffing until you've truly and utterly exhausted all other avenues (with the exception of using it to work around specific known quirks and bugs in old browsers, relating to behaviour that has since been fixed or standardised). The idea you expressed in the question, of simply not applying your click handler on certain browser versions, was misguided; you have no way of knowing (and nor do I) what other browsers share or will one day share Firefox's behaviour. If you'd taken your approach, it's almost inevitable that it would come back to bite you either when one of the major browsers followed Firefox's example or when one of your users tried to use your site on a Nintendo DS or something.

提交回复
热议问题