我刚开始使用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();
});发布于 2011-08-31 05:19:11
你已经很接近了,但还不是很好。使用jQuery的append()方法将新元素添加到包含元素的底部...
$('#kwdHelp').click(function() {
$('#outerElement').append(settingsDiv); // this very well could be $('body') or any element you choose
});..。调整您的样式,使其适合元素随后放置的位置。
发布于 2011-08-31 05:50:59
你也可以考虑类似这样的事情:
// 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。从一些良好的组织习惯开始总是很好的。
https://stackoverflow.com/questions/7249902
复制相似问题