JS动态创建<video>标签,未定义源时如何显示提示文本?
解决Video标签无流时显示提示文本的问题
浏览器支持video标签时,即使未设置视频源,也不会渲染video内部的子元素(这类子元素仅为不支持video的浏览器提供降级内容),所以你直接在video里添加p标签的方法无效。可以通过以下两种方式实现需求:
方法一:容器包裹+动态控制提示元素
创建容器容纳video和提示文本,默认显示提示,获取到远程流后隐藏提示:
// 第一步:创建容器、video和提示元素 const videoWrapper = document.createElement('div'); videoWrapper.style.position = 'relative'; videoWrapper.style.width = '320px'; videoWrapper.style.height = '240px'; videoWrapper.style.backgroundColor = '#f0f0f0'; // 预留区域背景色 const userAV = document.createElement('video'); userAV.autoplay = true; userAV.style.width = '100%'; userAV.style.height = '100%'; const tipText = document.createElement('div'); tipText.textContent = '视频无法访问'; tipText.style.position = 'absolute'; tipText.style.top = '0'; tipText.style.left = '0'; tipText.style.width = '100%'; tipText.style.height = '100%'; tipText.style.display = 'flex'; tipText.style.justifyContent = 'center'; tipText.style.alignItems = 'center'; tipText.style.color = '#333'; tipText.style.fontSize = '14px'; videoWrapper.appendChild(userAV); videoWrapper.appendChild(tipText); document.body.appendChild(videoWrapper); // 第二步:获取到远程流后执行 if (event?.streams[0]) { userAV.srcObject = event.streams[0]; tipText.style.display = 'none'; }
方法二:CSS伪元素(静态提示文本)
如果提示文本无需动态修改,可给video的父容器添加伪元素显示提示,获取到流后通过类名隐藏伪元素:
// 创建容器和video const videoWrapper = document.createElement('div'); videoWrapper.className = 'video-container'; videoWrapper.style.width = '320px'; videoWrapper.style.height = '240px'; const userAV = document.createElement('video'); userAV.autoplay = true; userAV.style.width = '100%'; userAV.style.height = '100%'; videoWrapper.appendChild(userAV); document.body.appendChild(videoWrapper); // 获取到流后给容器加类名,隐藏提示 if (event?.streams[0]) { userAV.srcObject = event.streams[0]; videoWrapper.classList.add('has-stream'); }
对应的CSS(可通过JS动态插入或写入样式表):
.video-container { position: relative; background-color: #f0f0f0; } .video-container::before { content: '视频无法访问'; position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; color: #333; font-size: 14px; } .video-container.has-stream::before { display: none; }
核心逻辑:浏览器不会渲染video内部的降级内容,因此必须通过外部元素提供无流时的提示,待成功设置视频源后隐藏该提示元素即可。
内容的提问来源于stack exchange,提问作者Tobic
相关产品推荐
相关产品推荐

