2016-08-22 2 views
0

私はDjangoのウェブサイトを利用しています。すべてのビデオはmp4形式でのみエンコードされます。ブラウザがこの形式(Firefoxなど)で再生できない場合は、エレガントなフォールバックをプログラムする必要があります。私にとって、それはストリーミングではなくビデオをダウンロードするオプションになります。JSを使用したhtml5ビデオのエレガントなフォールバック

単純なexample hereを見ると、私はDjangoテンプレートでフォールバックをプログラムしようとしましたが、役に立たないです。おそらくJSスニペットが微調整する必要があるでしょうか?

以下は、私のテンプレートコードの基本的な外観です。これを解決するために誰かが私を助けることができますか?前もって感謝します。

{% extends "base.html" %} 
{% block content %} 
<div class="margin"> 
<table> 

    {% for video in object_list %} 

    <tr><td> 
    <a name="section{{ forloop.counter }}"></a> 

    <a href="{% url 'videocomment_pk' video.id %}"> 
    {{ video.caption }} 
    <button> 
    Comment 
    </button>   
    </a> 

    <br> 
     <video width="500" height="350" controls autoplay> 
     <source src="{{ video.url }}" type='video/mp4; codecs="mp4v.20.8, samr"'> 
      <a href="{{ video.url }}"> 
       <img src="xyz.jpg" title="Your browser does not support the <video> tag"> 
      </a> 
     <p>Your browser does not support the <video> tag</p> 
     </video> 


     <br> 

    </td></tr> 

    {% endfor %} 
    </table> 
<script> 
var v = document.querySelector('video'), 
    sources = v.querySelectorAll('source'), 
    lastsource = sources[sources.length-1]; 
lastsource.addEventListener('error', function(ev) { 
    var d = document.createElement('div'); 
    d.innerHTML = v.innerHTML; 
    v.parentNode.replaceChild(d, v); 
}, false); 
    </script> 

</div> 
<br> 
{% endblock %} 

{% block pagination %} 
{% if is_paginated %} 
<div class="pagination"> 
    {% if page_obj.has_previous %} 
    &nbsp;&nbsp;&nbsp;<a href="?page={{ page_obj.previous_page_number }}#section0"><button>back</button></a> 
    {% endif %} 

    {% if page_obj.has_next %} 
    <a href="?page={{ page_obj.next_page_number }}#section0"><button >forward</button></a> 
    {% endif %} 
</div><br> 
{% endif %} 
{% endblock %} 

答えて

0

一つの問題は、ページ上に複数の要素を持っていることかもしれないが、あなたは例のページから取ったJSコードは、最初の要素だけを初期化します。

document.querySelectorAll('video')を使用して、各動画要素に対して繰り返し処理を行う必要があります。

EDIT - この汚いコードスニペットがうまくいくような何か:

var videos = document.querySelectorAll('video'); 
for (var i = 0; i < videos.length; i++) { 
    var v = videos[i]; 
    var sources = v.querySelectorAll('source'), 
     lastsource = sources[sources.length-1]; 
    lastsource.addEventListener('error', function(ev) { 
     var d = document.createElement('div'); 
     d.innerHTML = v.innerHTML; 
     v.parentNode.replaceChild(d, v); 
    }, false); 
} 
+0

クイックコメント:私は、これは正しい ''タグの後に、forloop *内側*スニペットのJS埋め込もうでした。技術的に、それはうまくいったはずですか? –

+0

'document.querySelector( 'video')を呼び出すたびに、最初の

+0

ちょうどあなたがそれを働かせる方法の例で私の答えを更新しました。 –

関連する問題