首页 > 解决方案 > 悬停在 Django 模板中的视频播放

问题描述

我通过迭代查询集对象来显示 Django 模板中的视频列表。我想在鼠标输入时播放特定的视频。

Django模板:

{% for video in videos %}
  <div class="card bg-light pl-3" style="width:310px;height:300px;border:none">
    <a href="{% url 'core:videoview' video.id %}"><video class="videocard" src="{{video.video_file.url}}" poster="{{video.thumbnail.url}}" alt="not found" style="height:185px" preload></a>
    <div class="card-body">
      <div class="row" style="">
          <div class="fst pt-2 pl-3">
            <img src="{{video.video_owner.channel_owner.profile_pic.url}}" class="rounded-circle" style="height:45px" alt="">
         </div>
         <div class="sec pt-2 pl-3">
           <tr>
             <p class="font-weight-bold""><a href="{% url 'core:videoview' video.id %}" style="text-decoration:none;color:black">{{video.video_title|truncatechars:"25"}}</a>
             <br>
             <a href="#" style="text-decoration:none;color:black"><span class="font-weight-normal">{{video.video_owner}}</span></a>
             </p>
           </tr>
         </div>
     </div>
   </div>
  </div>
{% endfor %}

JavaScript:

$(".videocard").on('mousenter', function(){
  $('.videocard').get(0).play();
  $('.videocard').get(0).currentTime = 0;
});

$(".videocard").on('mouseout', function(){
  $('.videocard').get(0).pause();
  $('.videocard').get(0).currentTime = 0;
});

但由于 get(0),它仅适用于视频列表中的第一个视频。如何使其适用于每个显示的视频?

标签: javascriptjquerydjangodjango-templates

解决方案


您可以在此处使用 event 关键字

$(".videocard").on('mousenter', function(event){
  event.target.play();
  event.target.currentTime = 0;
});

$(".videocard").on('mouseout', function(event){
  event.target.pause();
  event.target.currentTime = 0;
});

推荐阅读