简体   繁体   English

JavaScript覆盖在自定义html元素上

[英]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. 我试图制作一个简单的Overlay模块,使我能够将overlay放置在自定义DOM元素上。 The problem is that css for the overlay div specifies position:absolute. 问题是覆盖div的css指定position:absolute。 But element on which the overlay should be applied can have position:static in which case the overlay is applied incorrectly. 但是应该在其上应用覆盖的元素可以具有position:static,在这种情况下,覆盖被错误地应用。 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. 我在这里设置position:absolute而不指定top / left,这应该导致叠加层从流中移除,同时保持其偏移量。 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. 我提出的原始解决方案是一个真正的hack,已经给我带来了一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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