问题描述
我正在使用Nodejs,socket.io和WebRTC(peerjs库)开发视频聊天应用程序。在登录页面上,用户插入他/她的名字,并重定向到该页面,从而使他的视频流(通过WebRTC)并可以与他的同伴连接。一切正常,视频正在DOM中动态添加。每个同龄人加入后,我想使用Javascript在其视频的右下角动态添加每个登录用户的姓名。
JavaScrpt函数
//Function that appends all the videos to the DOM (Working fine)
const videoGrid = document.getElementById('video-grid');
const addVideoStream = (video,stream) => {
video.srcObject = stream
video.addEventListener('loadedMetadata',() => {
video.play()
})
videoGrid.append(video)
//Here I create a div,add the name in it and append on top of video
const testName = "John Doe"
const div = document.createElement('div');
div.classList.add('video-name');
const html = `
<i class="fas fa-microphone"></i>
<span>${testName}</span>
`
div.innerHTML = html;
video.appendChild(div);
}
<div class="main__videos">
<div id="video-grid">
{/* Add videos dynamically via Js */}
</div>
</div>
CSS
//CSS
//Parent Container that holds all videos
#video-grid{
display: flex;
width: 1090px;
overflow-y: auto;
flex-wrap: wrap;
position: relative;
}
//Each video
video{
height: 250px;
width: 350px;
object-fit: cover;
padding: 8px;
position: relative;
}
//Name styles that are being added dynamically
.video-name {
justify-content: end;
position:absolute;
left: 0;
z-index:1;
color: red;
background-color: orange;
}
解决方法
我想出了一个可能的解决方案。您在发布的代码中遗漏了;
,但我认为,如果您具有该功能,它们就会正确地发布在其中。
在这里,我为了测试目的创建了一个虚拟<div class="video"></div>
元素,而不是创建了<video>
标签元素。另外,我还更改了javascript的顺序,因此首先声明要添加视频和内部div的函数,然后使用空流创建虚拟视频元素,然后调用该函数。
在函数中,我首先得到一个videoGrid
元素,然后按原样运行代码。
我还相应地更改了CSS代码,以使用<div class="video">
元素而不是<video>
标签,并更改了video-name
和video
的某些属性元素。
//Function that appends all the videos to the DOM (Working fine)
const addVideoStream = (video,stream) => {
const videoGrid = document.getElementById('video-grid');
video.srcObject = stream;
video.addEventListener('loadedmetadata',() => {
video.play();
})
videoGrid.append(video);
//Here I create a div,add the name in it and append on top of video
const testName = "John Doe";
const div = document.createElement('div');
div.classList.add('video-name');
const html = `
<i class="fas fa-microphone"></i>
<span>${testName}</span>
`;
div.innerHTML = html;
video.appendChild(div);
}
const video = document.createElement('div');
video.classList.add('video');
const html = 'A video';
video.innerHTML = html;
addVideoStream(video,null);
#video-grid {
display: flex;
width: 1090px;
overflow-y: auto;
flex-wrap: wrap;
position: relative;
/* Added properties */
background-color: rgba(0,0.5);
color: black;
}
.video {
height: 250px;
width: 350px;
object-fit: cover;
padding: 8px;
position: relative;
/* Added properties */
border: dashed 1px black;
}
.video-name {
/* justify-content: end; <------- Removed */
position: absolute;
/* left: 0; <------- Removed */
z-index: 1;
color: red;
background-color: orange;
/* Added properties */
bottom: 0;
right: 0;
width: 50%;
}
<div class="main__videos">
<div id="video-grid">
The grid
</div>
</div>