我无法将下拉列表的默认值设置为最后一项。如果下拉列表中有3个项目,我希望第三个项目成为下拉列表的默认值。 html填充下拉列表的位置。
<div class='select'>
<select id='videoSource'></select>
</div>
javascript打开相机并在电脑上显示可用的相机。有人可以帮帮我吗?
<script type="text/javascript">
var videoElement = document.querySelector("video");
var videoSelect = document.querySelector("select#videoSource");
var startButton = document.querySelector("button#start");
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
function gotSources(sourceInfos) {
for (var i = 0; i != sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
var option = document.createElement("option");
option.value = sourceInfo.id;
if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources);
}
function successCallback(stream) {
window.stream = stream; // make stream available to console
videoElement.src = window.URL.createObjectURL(stream);
videoElement.play();
}
function errorCallback(error) {
console.log("navigator.getUserMedia error: ", error);
}
function start() {
if (!!window.stream) {
videoElement.src = null;
window.stream.stop();
}
var videoSource = videoSelect.value;
var constraints = {
video: {
optional: [{ sourceId: videoSource}]
}
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
videoSelect.onchange = start;
start();
答案 0 :(得分:0)
最简单的解决方案是在你在gotSources函数中添加新选项后添加
videoSelect.value = sourceInfo.id;
所以它会读
if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
videoSelect.value = sourceInfo.id; //update the value to the last element
} else {
console.log('Some other kind of source: ', sourceInfo);
}
这将为每个添加的新选项设置它(不是最“有效”的解决方案,但绝对不会遇到性能下降)。如果您想要一次性地发出值设置命令,则需要存储添加的最后一个选项并将其设置在for循环之外。
再一次,可能不值得,但是你的电话。
答案 1 :(得分:0)
对于最后一个选项,将 selected
属性设置为中 true
>循环。
if( i == sourceInfos.length - 1 ) {
option.selected = true;
}