javascript - Setting the value of video src dynamically through jquery cannot play the video?
过去多啦不再A梦
过去多啦不再A梦 2017-05-16 13:43:02
0
6
2840
<p id="video-box">
 <video style="object-fit: fill;width: 200px;height: 50px;" controls>
    <source src="">
  </video>
</p>
<a class="dj" href="javascript:;" src="http://www.w3school.com.cn/i/movie.mp4">点击</a> 
*{padding:0;margin:0;}
#video-box{display:none;}
$(".dj").on("click", function() {
   var src = $(this).data("src");
   $("#video-box source").prop("src",src)
   $("#video-box").show();
});

The demo is here https://jsfiddle.net/r9u1cn7o/
Make a pop-up box to play the corresponding video by clicking on different labels, but I successfully assigned a value to src through jquery, but I don’t know why it can’t be played. ?

过去多啦不再A梦
过去多啦不再A梦

reply all(6)
为情所困

The src value of the source is indeed assigned successfully through jQuery. From the debugging point of view, the browser does not initiate a request to obtain the corresponding video, but simply assigns the value in the src of the a tag to the source.

But if you do this, the browser will request the address to get the video file:

$(".dj").on("click", function() {
   var src = $(this).data("src"),
       sourceDom = $("<source src=\""+ src +"\">");
       
   $("#video-box video").append(sourceDom);
   $("#video-box").show();
   
   // 自动播放
   $("#video-box video")[0].play()
});

Therefore, it can be inferred that when there is a source tag in the video, the browser will automatically obtain the address after rendering. Even if the address changes, the browser will not obtain the address again. However, by dynamically inserting the source tag, the browser can be triggered to reflow, thereby obtaining the file at the corresponding address for playback.

小葫芦
<video>
    <source src="xxx.mp4"/>
    <source src="xxx.ogg"/>
</video>

The src in source will only be checked once during rendering.
To dynamically adjust src, you should start with video. If you change it to this, it should be fine
$("#video-box video").prop(" src",src)

为情所困

Don’t use the source tag, write it directly into the video tag; use attr() instead. Also, don’t write the width and height of the video tag in the style, take them out~

習慣沉默

jsfidle cannot embed videos. Just change it to local

曾经蜡笔没有小新

The video formats supported by the video tag include (1) H.264 encoded mp4 files (2) webm (3) ogg. Files with other suffixes are temporarily not supported due to patent issues and other issues. You can consider transcoding and try it

我想大声告诉你

Just add a play() event

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!