2014-09-06 39 views
1

我的簡單Chrome擴展插件是在document.body的頂部注入一個DIV,然後您可以將文本從您的頁面拖到擴展中。問題是我希望擴展DIV不要位於頂部,而應該像左側的側欄。通過操縱加載的網頁的DOM創建邊欄

換句話說,我需要知道如何以編程方式重新排列已經加載的DOM結構,以便將所有內容移動到右側並進行水平壓縮,然後左側區域可以進一步操作。我正在考慮

一個方案是要做到這一點:

tmp = document.body.innerHTML 
document.body.innerHTML = '<table><tr><td id=sidebar></td><td>' 
    + tmp + '</td></tr></table>' 

但是,這將是inneficient,會導致重新呈現,並可能有其他不良副作用。

順便說一下,當前版本的擴展插件將在「加載」時注入每個頁面,但這只是一個臨時解決方案,單擊擴展按鈕時必須顯示側欄。這不是這個問題的一部分,我知道如何做到這一點。只是爲了讓您知道,當用戶選擇單擊按鈕時,可以隨時完成側邊欄創建。這就是爲什麼使用innerHTML不是一個好的選擇。


pageload.js

function allowDrop(ev) {ev.preventDefault()} 

function drop(ev) { 
    ev.preventDefault(); 
    var t = 'text', T = Array.prototype.slice.apply(ev.dataTransfer.types) 
    if (T.indexOf('text/html') >= 0) 
     t = "text/html" 
    console.log('text type:', t) 
    d1.innerHTML += '<div style="display:inline;border:2px solid #000000;">'+ev.dataTransfer.getData(t)+'</div> ' 
} 

function createDragbar(id) { 
    var n = document.createElement('div') 
// n.style.position = "absolute"; 
    n.setAttribute('id', id) 
    n.style.border = '1px solid #aaaaaa' 
    n.style.height = 532 
    n.style.background = "teal" 
    n.innerHTML = "Drop your text here " 
    n.ondrop = drop 
    n.ondragover = allowDrop 
    document.body.insertBefore(n, document.body.firstChild) 
} 
createDragbar('d1') 

的manifest.json

{ 
    "name": "Yakov's Demo Extension", 
    "description": "Just a demo", 
    "version": "0.1", 
    "permissions": [ 
     "activeTab" 
    ], 
    "content_scripts": [{ 
     "matches": ["http://*/*", "https://*/*", "file://*/*"], 
     "js": ["pageload.js"] 
    }], 

    "manifest_version": 2 
} 
+0

您應該注入一個框架以避免造型,JavaScript碰撞。 – abraham 2014-09-08 01:21:51

回答