【发布时间】:2021-01-22 17:44:30
【问题描述】:
我在 foreach 循环中有几个这样的 html 块:
<label class="">Replace video:</label>
<input type="file" name="replaced_main_video" class="input-video-preview" />
<!-- replaced main video -->
<video class="video" controls>
<source type="video/mp4">
</video>
<canvas></canvas>
<label class="">Preview replaced video:</label><br />
<img class="video-preview" width="100" src="#" />
要显示上传的所选视频的预览,请使用以下 js 代码:
$(function() {
var video = $('.video');
var thumbnail = $('canvas');
var input_video_preview = $('.input-video-preview');
var ctx = thumbnail.get(0).getContext("2d");
var duration = 0;
var img = $('.video-preview');
input_video_preview.on('change', function(e) {
var file = e.target.files[0];
// Set video source
video.find('source').attr('src', URL.createObjectURL(file));
// Load the video
video.get(0).load();
// Load metadata of the video to get video duration and dimensions
video.on('loadedmetadata', function(e) {
duration = video.get(0).duration;
// Set canvas dimensions same as video dimensions
thumbnail[0].width = video[0].videoWidth;
thumbnail[0].height = video[0].videoHeight;
// Set video current time to get some random image
video[0].currentTime = Math.ceil(duration / 2);
// Draw the base-64 encoded image data when the time updates
video.one("timeupdate", function() {
ctx.drawImage(video[0], 0, 0, video[0].videoWidth, video[0].videoHeight);
//$('.video-preview').attr("src", thumbnail[0].toDataURL());// THIS WORKS, but all imgs get src
$('.input-video-preview').next('.video-preview').attr("src", thumbnail[0].toDataURL()); // bind to the next img with class 'video-preview'
});
});
});
});
这很好用,但是因为 html 块由 foreach 重复,所以每个 img 都会获取源代码。我只想要input type="file"之后的下一个img标签
我尝试在函数中使用下面的这一行来实现这一点:
$('.input-video-preview').next('.video-preview').attr("src", thumbnail[0].toDataURL()); // get input with class 'input-video-preview', take the next img with class '.video-preview' and bind it to the `src` attribute
但不幸的是,这不起作用.... 我怎样才能做到这一点?
【问题讨论】:
标签: jquery image find src next