Javascript:视频弹出窗口

标签 javascript html css

我想编写一个运行如下的 javascript 函数:

输入:Youtube 视频 ID(即 F3v39wnv)、高度、宽度和名称

Action :弹出一个新窗口,指定宽度和高度,显示指定的视频。

我已经想出了一个基本的方法(通过使用 document.write() ),但我知道这会使页面容易出现漏洞。

我是一个很强的程序员,我只是一点都不熟悉 javascript。将参数传递给新网页的标准方法是什么?我已经能够让源页面生成包含所有指定参数的新窗口,如下所示:videoplayer.htm?vid=(VidID)?height=(height)?width=(width)?name=(name),但我无法从 videoplayer.htm 中读取这些参数

谢谢!

最佳答案

您可以使用 window.location。更具体地说,window.location.pathname 将返回主机名后面的所有内容。在此页面中,这将是“questions/4856801/javascript-video-pop-up-window”

然后您可以使用 String.split 方法将 url 拆分为其参数

var arguments = window.location.pathname.split("?")[1].split("&");

应该将 "videoplayer.htm?vid=3&height=4&width=5"拆分为 ["vid=3", "height=4", "width=5"]

然后用“=”字符进一步拆分每个参数应该给你一个标签=>值数组 "vid=3".split("=") 变成 ["vid", "3"]


function fetchArguments() {
    var arg = window.location.pathname.split("?")[1].split("&"), // arguments
        len = arr.length, // length of arguments
        obj = {}, // object that maps argument id to argument value
        i, // iterator
        arr; // array

    for (var i = 0; i < len; i++) {
        arr = arg[i].split("="); // split our first argument
        obj[arr[0]] = arr[1]; // e.g. obj["vid"] = "3"
    }

    return obj;
}

function loadVideo() {
    var args = fetchArguments(),
        iframe = document.createElement("iframe");

    iframe.title = "YouTube video player";
    iframe.width = args["width"];
    iframe.height = args["height"];
    iframe.src = "youtube.com/embed/" + args["vid"];
    iframe.type = "text/html";
    iframe.className = "youtube-player";
    // I'm sure you get the idea

    document.getElementsByTagName("body")[0].appendChild(iframe); // we append the iframe to the document's body
}

所以我不确定你到底想用 iframe 做什么,但在我的示例中,loadVideo() 函数将创建一个元素并将其附加到文档的主体

关于Javascript:视频弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4856801/

相关文章:

html - 三个div的水平对齐

html - 如何使容器 div 与其中的 h1 元素一样宽

templates - 是否可以将 CSS3 框阴影内联应用于 HTML 电子邮件?

javascript - 在 jQuery 弹出式 div 中显示图像

javascript - Node.js/Express/Jade Javascript 未按正确顺序加载

javascript - 带有数组获取变量的 $.post 语法

javascript - 将 XML 集成到 iOS Web App 的 HTML 页面中

html - 创建一个带有 CSS 样式的盒子

html - 调整列表项上背景 Sprite 图像的大小

javascript - Meteor - 箭头函数打破 ES6 中的 #each 循环