2017-01-10 45 views
0

今天是我第一次使用JavaScript和jQuery。将YouTube手表<a>替换为<iframe>嵌入视频

我有使用HTML,PHP,Python,CSS的经验。

根据我的经验,我发现最好的学习方法就是一边学习,一边学习。

我对Chrome扩展有一个想法(没有线索,如果它是原创的,我只是想学习),在YouTube上,您将鼠标悬停在视频链接上,并将视频加载到iframe中。点击获取它并不是我正在做的。目前我只是使用悬停。但是,我不知道如何使它成为一个iframe。

manifest.json的

{ 
    "name": "HoverTube", 
    "description": "Hover over any video on YouTube and it will begin to play without even having to click it. Perfect for those who are tight on resources, and don't want to load a whole new page for just 1 video.", 
    "version": "0.2", 
    "manifest_version": 2, 

    "content_scripts": [ 
    { 
     "matches": [ 
     "https://www.youtube.com/*" 
     ], 
     "js": ["jquery-3.1.1.min.js", "hover.js"] 
    } 
    ] 
} 

hover.js

$('body').on('mouseenter', 'a', function(){ 
    if (this.href.includes("watch")){ 
      //Take this.href and convert it to <iframe width="560" height="315" src="https://www.youtube.com/embed/linkfromthehref" frameborder="0" allowfullscreen></iframe> 
     } 

    }) 

回答

1

你可以使用jQuery的.replaceWith()方法只使用iframe作为HTML文本与URL替换<a>使用改性.replace() and a regular expression

$('body').on('mouseenter', 'a', function(){ 
    if (this.href.includes("watch")){ 
     $(this).replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/' +this.href.replace(/[^=]*=/,'')+'" frameborder="0" allowfullscreen></iframe>'); 
    } 
}) 

除了插入它,你应该给它一个ID。从UI的角度来看,选择页面上的一个位置来显示iframe并重新使用该位置可能会更好。更有可能的是,当链接悬停时,只有显示iframe的弹出/弹出窗口,然后在链接不再徘徊时将其销毁。

+0

@我将重新阅读您的问题并更新答案,以真实反映您所要求的内容(即替换,而不是添加'