仅在第一个元素上悬停播放视频

Play video on hover only working on the first element

当鼠标悬停在 div 上时,将播放视频。一切正常,但视频只在第一个“播放器”上播放。我可以看到每个播放器的缩略图,但他们没有开始播放。为什么会这样?

<?php
    foreach($posts as $post)
    {
      $vimeoid = get_field('film_vimeo', $post, true);
      if (empty($vimeoid)) 
      {
        $projektclass = "not-vimeo";
      }
      else 
      {
        $projektclass = "vimeo";
      } 

      //echo '<div id="hp-post"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></div>';
      echo '<div class="'.$projektclass.'" style="position: relative;" id="hp-post">';
      echo get_the_post_thumbnail( $post, 'full' );
      echo '<div id="'.$vimeoid.'"><iframe class="vimeoplayer" id="'.$vimeoid.'" style="position: absolute; z-index:-1;" src="https://player.vimeo.com/video/'.$vimeoid.'?title=0&byline=0&portrait=0&background=1&autoplay=0 width="100%" height="0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div></div>';
    }
    echo '</div>';
  }
?>
jQuery(document).ready(function() {
  var vimeo = document.getElementsByClassName('vimeo')[0];
  var player = new Vimeo.Player(vimeo);

  vimeo.onmouseover = function() {
    return player.play();
  };
  
  vimeo.onmouseout = function() {
    return player.pause();
  };
});

问题是因为您只检索元素集合中的第一项(即 [0] 项)并将事件绑定到该项。 None 的其他元素受到影响。要解决此问题,您需要遍历它们。

我还建议为此使用 addEventListener() 而不是 onX 事件属性。试试这个:

jQuery($ => {
  Array.from(document.getElementsByClassName('vimeo')).forEach(el => {
    let player = new Vimeo.Player(el);
    el.addEventListener('mouseover', () => player.play());
    el.addEventListener('mouseout', () => player.pause());
  });
});