显示几个背景视频

时间:2016-03-25 08:52:17

标签: javascript html5 html5-video

我正在尝试使用Javascript和createElement方法显示不同的背景视频,只有一个视频标记节点。通过单击链接,可以很好地显示视频,但不能显示其他视频。我还检查了DOM元素,并且<video> + <source>标签的两个元素(id和src)都已经很好地切换(movie1&gt; movie2)。即使在DOM Elements中对元素进行了很好的修改,看起来浏览器仍保留第一个视频。

<head>
    <script>
        var movieNow = "";
        function playVideo(movie, mp4) {
            if (movieNow!="") {
                document.getElementById(movieNow).pause();
                document.getElementById(movieNow).style.display="none";
                document.getElementById(movieNow).id = movie;
                document.getElementById('mysource').src = "videos/"+mp4+".mp4";
                document.getElementsByTagName("Video").play();
                    document.getElementsByTagName("Video").style.display="block";
            } else {
                bckMovie = document.createElement("video");
                bckMovie.id = movie;
                bckMovie.className = "myvideo";
                bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
                document.body.appendChild(bckMovie);
                document.getElementById(movie).style.display="block";
                document.getElementById(movie).play();
            }
            movieNow = movie;
        }
    </script>
<body>
    <a href="javascript:playVideo('movie1', 'movie123')">Movie 1</a>
    <a href="javascript:playVideo('movie2', 'movie456')">Movie 2</a>
    ...
</body>

1 个答案:

答案 0 :(得分:0)

嗯,你有一些逻辑问题......请在JsFiddle检查这段代码,这看起来很有用。 documentation

<head>
    <script>
    var movieNow = "";
     function playVideo(mp4) {
        var movieNow = document.getElementById("movie");
        if (movieNow !== null) {
            movieNow.pause();
            movieNow.style.display="none";
            document.getElementById('mysource').src = "videos/"+mp4+".mp4";
            movieNow.play();
            movieNow.style.display="block";
        } else {
            bckMovie = document.createElement("video");
            bckMovie.id = "movie";
            bckMovie.className = "myvideo";
            bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
            document.body.appendChild(bckMovie);
            document.getElementById("movie").style.display="block";
            document.getElementById("movie").play();
         }
     }
     movieNow = movie;
</script>
<body>
    <a href="javascript:playVideo('movie123')">Movie 1</a>
    <a href="javascript:playVideo('movie456')">Movie 2</a>
    ...
</body>