Video-js点击事件优化:如何避免触发控制栏按钮
Hey there! I totally get where you're coming from—when you're just starting out with Video.js, it's easy to run into little quirks like this. Let's fix that click event issue so it only triggers when you tap/click the actual video area, not the control bar buttons.
Option 1: Check if the Click Originated from the Control Bar
This is the most reliable approach because it uses Video.js's built-in API to access the control bar element, so you don't have to worry about class names changing in future versions. Here's how to do it:
var player = videojs('videojs-player', {}, function() { // Your initialization code here }); // Use 'pointerup' to handle both mouse clicks and mobile taps player.on('pointerup', function(e) { // Get the control bar DOM element using Video.js's API const controlBar = player.controlBar.el(); // Check if the clicked element is part of the control bar if (controlBar.contains(e.target)) { // Exit early if we clicked a control button return; } // Your logic to switch to the next video goes here alert('video area was clicked/tapped'); });
Option 2: Bind Directly to the Video Element
If you prefer targeting the actual video playback area directly, you can select the .vjs-tech element (this is the underlying <video> or <iframe> element Video.js uses) and bind your event there. Just make sure to do this inside the player's ready callback to ensure the element exists:
var player = videojs('videojs-player', {}, function() { // Get the video playback element const videoElement = this.el().querySelector('.vjs-tech'); // Bind click/tap event videoElement.addEventListener('pointerup', function(e) { // Stop the event from bubbling up to the player (prevents default play/pause) e.stopPropagation(); // Your next video logic here alert('video was clicked/tapped'); }); });
Why This Works
- The first option checks if the clicked element is a child of the control bar using
contains()—if it is, we skip our custom logic. - The second option targets only the video playback area, so control bar clicks never trigger our event at all. The
e.stopPropagation()ensures Video.js's default play/pause behavior doesn't run either, which is exactly what you want since you're overriding that action.
Either approach should solve your problem—pick the one that feels more intuitive to you!
内容的提问来源于stack exchange,提问作者Erick

