【问题标题】:Load video on image click in subpage在子页面点击图片加载视频
【发布时间】:2020-08-30 04:56:45
【问题描述】:

我正在使用 html、css 和 javascript 开发一个静态投资组合网站。 在index.html 我有一个图片库。每个图像代表一部电影。单击图像时,用户将被定向到detail.html 页面,该页面应该在 iframe 中显示特定视频以及引用数据。 但是,当单击index.html 页面中的图像时,我正在努力将视频加载到detail.html 页面中。它加载页面但不加载视频。 这是index.html的html代码:

  <a href="#" onclick="myFunction()">
            <img alt="picture" src="img/portfolio/filmcity.jpg" width="100%" />
   </a>

这是 Javascript:

function myFunction() { 
  window.location = 'detail.html';
  var video = document.getElementById("myFrame");
  video.setAttribute("src", "https://www.youtube.com/embed/Jiu42WJ9Vdk");
}

这是detail.html的html代码:

<iframe width="100%" id="myFrame" height="60%" src="">
</iframe>

有人可以帮忙吗?

【问题讨论】:

  • 我不确定您要问的是什么。因此,您希望父页面从 index.html 转到 detail.html 并在 detail.html 中将视频加载到 iframe 中?
  • 是的,@imvain2 这可能吗?

标签: javascript html css portfolio


【解决方案1】:

所有指向 detail.html 的链接的 URL 如下:detail.html?video_id=XXXXX 其中 XXXXX 是您要链接到的 youtube id。

<a href="detail.html?video_id=Jiu42WJ9Vdk"> Watch video </a>

Detail.HTML

<iframe width="100%" id="myFrame" height="60%" src="about:blank;"></iframe>

JAVASCRIPT:

function _get(name) {
    url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return "";
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var _youtube_id = _get("video_id");

if (_youtube_id.match(/^[0-9a-z]+$/)){
  var video = document.getElementById("myFrame");
  video.setAttribute("src", "https://www.youtube.com/embed/" + _youtube_id);
}

【讨论】:

    【解决方案2】:

    您无法在旧页面上运行功能时导航到新页面。 JavaScript 不是这样工作的。您需要在其运行的页面上的页面加载时调用您的函数。也许是这样的:

    在 index.html 上

    <!-- include the video ID as a URL parameter -->
    <a href="detail.html?vid=Jiu42WJ9Vdk"> ... </a>
    

    关于detail.html

    <iframe width="100%" id="myFrame" height="60%" src=""></iframe>
    
    <script>
    // get the video ID from the URL and use it in the iframe source string
    let url = new URL(window.location.href);
    let vid = url.searchParams.get("vid");
    let videoEl = document.getElementById("myFrame");
    video.setAttribute("src", "https://www.youtube.com/embed/" + vid);
    </script>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多