2017-01-10 58 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

@我將重新閱讀您的問題並更新答案,以真實反映您所要求的內容(即替換,而不是添加'