jQuery - How Do I Place a DIV On Overlay?

坚强是说给别人听的谎言 提交于 2019-12-03 15:35:38

问题


I'm trying to make a modal dialog in the least amount of jQuery code as possible because my project already has a bit too much jQuery loaded into it.

So, I first needed an overlay, which is achieved with:

$('body').wrapInner('<div />')
.css('opacity','0.5')
.css('z-index','2')
.attr('id','dim1');

Disregard for now that I have another routine to kill the click events on #dim1 while this modal is present. So, now I need to draw my modal dialog on top:

$('body').append('<div id="test">My Test</div>');
$('#test')
.css('opacity','1.0')
.css('position','fixed')
.css('color','#000')
.css('z-index','2000')
.css('height','300px')
.css('width','300px')
.css('top','50%')
.css('left','50%');

However, when I do this, I end up with a dimmed out #test, when I don't want that to be dimmed -- just the stuff behind it. What's the trick?


回答1:


See this quick demo here, the key lies to the modal being absolute over the top of the opaque background. The demo dynamically adds the background overlay div and the modal div to the body but you could define these in the html and just show them.

Agreed there is no need to use a plugin for a modal effect, most of the plugins come with lots of options hence the bloat which you do not want if you only need the simplest of effects. - Note we can do this in two lines rather than 3 - and without a plugin!!

Also it is far easier to define css classes and add these rather than add inline styles to an element in script. Easier to maintain.




回答2:


I think your best solution might be to use a jquery plugin. A quick google search threw up this: http://www.ericmmartin.com/simplemodal/ which is doing what you need in three lines!

If you want some more, there are loads on the jquery overlays plugin page

From the look of it, the CSS is the key to getting things right, and most of these examples should come with demo CSS for you to adapt.

Obviously this brings in more external jquery code which you are concerned about - but I would suggest a well written and stable plugin would save you lots of work/time/lines of code!



来源:https://stackoverflow.com/questions/383116/jquery-how-do-i-place-a-div-on-overlay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!