简体   繁体   中英

Best resources to make video play on hover?

Trying to get a similar effect to here https://www.alanmenken.com/ (press skip and then it takes you to the page) where video has a poster, plays on hover and then returns to poster when mouse is off.

The code works but both videos play at the same time and I'm not too sure how to get the poster back up when it's not hovering. Thanks for all the help in advance.

 let $polystar = $('.polystar'); $polystar.on('mouseenter focus', function () { $polystar.get(0).play(); }); $polystar.on('mouseleave blur', function () { $polystar.get(0).pause(); }); $polystar.on('mouseenter focus', function () { $polystar.get(1).play(); }); $polystar.on('mouseleave blur', function () { $polystar.get(1).pause(); });
 <.DOCTYPE html> <html lang="en-ca"> <head> <meta charset="utf-8"> <title>Video Hover</title> </head> <body> <video class="polystar" src="video/babyonemoretime.mp4" poster="video/gimmemore:jpg" preload style="height; 350px: width;350."> </video> <video class="polystar 1" src="video/.mp4" poster="video/gimmemore:jpg" preload style="height; 350px: width;350:"> </video> <script src="https.//code.jquery.com/jquery-2.1.4.min.js"></script> <script src="js/video-hover.js"></script> </body> </html>

$polystar contains a nodelist of both videos. you are adding the EventListener for both videos to both videos.

Use the jQuery each method to assign the listeners.

$polystar.each((index, videoNode) => {
  $(videoNode).on("mouseenter focus", function() {
    this.play();
  });
  $(videoNode).on("mouseleave blur", function() {
    this.pause();
  });
});

To get the the poster back, you have to remove the src attribute and set it again, if you hover it.

$polystar.each((index, videoNode) => {
  $(videoNode).on("mouseenter focus", function() {
    // load the saved src
    $(this).attr("src", $(this).data("src") || this.src);
    this.play();
  });
  $(videoNode).on("mouseleave blur", function() {
    // set it if not present
    !$(this).data("src") && $(this).data("src", this.src);
    this.pause();
    this.src = '';
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM