我希望用户从提示中输入,以更改iframe网址的最后一部分。到目前为止,我的代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color:#ffffff
}
</style>
</head>
<body>
<!-- im attempting to make an iframe display a video the user types into
the prompt.-->
<p id="Video"></p>
<script>
var VideoURL = prompt("type the last part of the YouTube.com video
URL here");
if(VideoURL != null){
document.getElementById("Video").innerHTML= "you typed '' " +
VideoURL + " '' as your url.";
} else {
alert("please reload and type a URL.");
}
</script>
<iframe src="www.youtube-nocookie.com/embed/(I WANT THE USERS INPUT
HERE)" allowfullscreen></iframe>
</body>
</html>
我已经做了三天了,但还是搞不清楚。请帮帮忙。
发布于 2017-04-10 14:40:57
您只是在脚本的末尾遗漏了一行,它设置了src
属性的iframe
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color:#ffffff
}
</style>
</head>
<body>
<!-- im attempting to make an iframe display a video the user types into
the prompt.-->
<p id="video"></p>
<iframe src="www.youtube-nocookie.com/embed/" allowfullscreen></iframe>
<script>
// By placing the script just before the end of the <body>, all the DOM elements will
// have loaded by the time the script runs.
// Get user input:
var videoURL = prompt("type the last part of the YouTube.com video URL here");
if(videoURL != null){
// Get a reference to the iframe and reset its src property:
var frame = document.querySelector("iframe");
frame.src = frame.src + videoURL;
// Output the new URL
document.getElementById("video").innerHTML= "New src is: " + frame.src;
} else {
alert("please reload and type a URL.");
}
</script>
</body>
</html>
发布于 2017-04-10 14:46:34
可以使用src
更改<iframe>
的JavaScript属性,我认为这是解决问题的最佳方法。
首先,我建议为您的<iframe>
提供一个id
,以便于检索。
例如:<iframe id="youtubePlayer" allowfullscreen></iframe>
如果将用户输入存储在变量VideoURL
中,则可以使用以下代码行修改<iframe>
的src
document.getElementById('youtubePlayer').src = "www.youtube-nocookie.com/embed/" + VideoURL;
首先我们使用document.getElementById()
检索元素,然后通过给.src
赋值来修改源。
我希望这有帮助:)
发布于 2017-04-10 14:37:45
您将不得不通过一个JavaScript变量分配URL的最后一部分,因为当HTML呈现时,页面加载时不会有它。最简单的方法是将ID分配给您的iframe --例如,videoFrame
--然后您就可以这样做:
document.getElementById('videoFrame').src = "www.youtube-nocookie.com/embed/" + VideoURL;
https://stackoverflow.com/questions/43325718
复制相似问题