简体   繁体   中英

plain javascript: overlay object

There is any object (could be an inline object like but also a block element like or ) as original object.

Now I try to set an overlay over this object, with the same position and size.

=> function overlayObject(originalObject)

Creating the new overlay and mirroring the size of the original object works well. I can also append this new element within the originalObject's parent node.

Regarding the position, left+top for achieving the overlay, is still pending and failing. With original objects that have position:absolute or position:fixed, it's easy, but how to get the exact left/top position to use the same with the overlay ?

You can use offsetTop and offsetLeft to determine the top and left distance of your element to the parent element:

Fiddle

function createOverlay(el) {
    var t = el.offsetTop;
    var l = el.offsetLeft;
    var newEl = el.cloneNode(true);
    newEl.style.margin = "0";
    newEl.style.position = "absolute";
    newEl.style.left = l + "px";
    newEl.style.top = t + "px";
    newEl.style.backgroundColor = "rgba(0,0,255,0.3)";
    el.offestParent.appendChild(newEl);
}

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