2011-08-30 64 views
2

我是新來的使用Greasemonkey和jQuery,我需要添加一個設置面板到當前頁面,當圖像被點擊。創建一個div,並通過Greasemonkey和jQuery將其添加到頁面

有人能給我一個如何通過jQuery創建div的例子,然後將其添加到當前頁面,絕對定位在其他元素?

下面是我正在使用的一些測試代碼,有點盲目地涉及到的方法。

var settingsDiv = '<div style="position:absolute;bottom:0;width:500px;padding:0;" id="kwdHelpInfo">This is the div that I want to add to the page</div>'; 

//the #kwdHelp element is an image file already in the document. When its clicked, I want to show the settingsDiv... 

jQuery('#kwdHelp').live('click',function(){ 
    //alert('clicked show help'); 
    //var newcell = jQuery(settingsDiv); 
    //jQuery(newcell).show(); 
}); 

回答

2

你很接近,但並不完全在那裏。使用jQuery的append()方法到新的元素添加到包含元素的底部...

$('#kwdHelp').click(function() { 
    $('#outerElement').append(settingsDiv); // this very well could be $('body') or any element you choose 
}); 

...因爲酒店的套房,其中元素,然後定位調整你的造型。

+0

+1夠簡單。謝謝! – RegEdit

+0

很高興我能幫到你。 :) – 65Fbef05

1

您也可以考慮這樣的:

// Create, Append, and Save jQuery object for later reference 
// Using appendTo is similar to append in functionality, but it returns the object appended 
// Create once; toggle later 
var jQ_helpInfo = jQuery("<div id='kwdHelpInfo'> ... </div>").appendTo("body"); 

// ...potentially add styles here... 

// Add the click live event to "show" 
jQuery("#kwdHelp").live("click", function() { jQ_helpInfo.show(); }); 

// Later you can have another event "hide" 
jQuery(/* some other element or selector */).live("click", function() { jQ_helpInfo.hide(); }); 

通常情況下,我會建議在風格樣式表,或者至少<style>標籤......然而,在Greasemonkey的,它實際上過度複雜的東西嵌入此風格辦法。您還可以組織你的風格與對象...

// Define styles 
var helpInfo_CSS = { 
     "position": "absolute", 
     "bottom": 0, 
     "width": "500px", 
     "padding": 0 
    }; 

// Now apply the styles 
jQ_helpInfo.css(helpInfo_CSS); 

這當然不是規則,而是因爲你提到的是新來的jQuery和Greasemonkey的我加入這個額外的建議。以一些良好的組織習慣開始總是很好的。

相關問題