简体   繁体   中英

javascript overlay on a custom html element

I am trying to make a simple Overlay module that would enable me to put overlay on a custom DOM element. The problem is that css for the overlay div specifies position:absolute. But element on which the overlay should be applied can have position:static in which case the overlay is applied incorrectly. How to overcome this issue? I have come up with this but I am not sure if it is good.

//js
if ($(elem).css('position') == 'static') {
   $(elem).css('position', 'relative');
}
$('<div></div>').prependTo(elem).addClass('overlay').css('z-index', 100);

// css
div.overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000;
    opacity: 0.75;
    filter: alpha(opacity=75);
}

The suggestion of Thomas Andersen works. A slight disadvantage is a bit higher complexity and that position of the overlay is not pinned to the position of the element. Another approach could be to do it like this:

div.overlay {
    position: absolute;
    background: #000;
    opacity: 0.75;
    filter: alpha(opacity=75);
}

var width = $(elem).width();
var height = $(elem).height();
$('<div></div>')
    .width(width)
    .height(height)
    .prependTo(elem)
    .addClass('overlay')
    .css('z-index', 100)

Here I am setting position:absolute without specifying top/left which should cause the overlay to be taken out of the flow while keeping its offset. Uncommon usage, I guess, but I believe I can rely on this.

The original solution I have proposed is a real hack and caused me some problems already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM