使用javascript,通过点击事件对ID进行切换?

时间:2019-04-02 14:19:55

标签: javascript jquery html html5 html5-video

我有一个简单的块,其中包含两个视频元素,我有一个暂停按钮,当用户单击“暂停”按钮时,它会暂停当前播放的视频。

不幸的是,我的方法不起作用。我的代码在做什么错了?

document.querySelector("#video-pause_btn").addEventListener('click', function() {
  console.log(($(this).attr('id')))
  switch ($(this).attr('id')) {
    case 'video-player_not-transformed':
      pauseVideo();
      break;
    case 'video-player_transformed':
      pauseTransfromedVideo();
      break;
  }
});

var pauseVideo = function() {
  var videoNotTransformed = document.querySelector('#video-player_not-transformed');
  videoNotTransformed.pause();
};

var pauseTransfromedVideo = function() {
  var videoTransformedID = document.querySelector('#video-player_transformed');
  videoTransformedID.pause();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video-container">
  <div class="video-container_details">
    <div id="video-pause_btn" class="video-btn">
      <img src="images/stop.png" />
    </div>
  </div>
  <div class="video-conatiner_datavideo">
    <video class="videoplayer" id="video-player_not-transformed">
      <source src="videos/explainer.mp4" type="video/mp4">
    </video>
  </div>
  <div class="video-container_transformed">
    <video id="video-player_transformed" style="width: 300px; height:auto; padding: 30px;">
      <source src="videos/transformed.mp4" type="video/mp4">
    </video>
  </div>

1 个答案:

答案 0 :(得分:0)

您的切换逻辑被破坏了,因为$(this).prop('id')只会返回video-pause_btn,因为这是您将事件处理程序分配给的元素。

一种更好的方法是使用filter()确定当前正在播放的视频,然后将其暂停并开始播放其他视频,如下所示:

var $videos = $('video');

$('#video-pause_btn').on('click', function() {
  var $playing = $videos.filter(function() {
    return !this.paused;
  }).get();

  if ($playing.length === 0) {
    $videos.first()[0].play();
  } else {
    $playing[0].pause();
    $videos.not($playing)[0].play();
  }
});
video {
  width: 250px;
  height: auto;
  padding: 10px;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video-container">
  <div class="video-container_details">
    <div id="video-pause_btn" class="video-btn">
      Play/pause
      <img src="images/stop.png" />
    </div>
  </div>
  <div class="video-conatiner_datavideo">
    <video class="videoplayer" id="video-player_not-transformed">
      <source src="https://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
    </video>
  </div>
  <div class="video-container_transformed">
    <video id="video-player_transformed">
      <source src="https://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
    </video>
  </div>
</div>