How to cut a part of div

I try to give you a broad picture of my problem. Suppose I have a overlay div on my page with z-index: 99; , with background-color: rgba(0,0,0,0.5) . Then I want to remove a part of overlay div , for example 100 x 100px in top: 50px; and left: 200px; .

By removing I mean that exclude a part of overlay div to make that part visible and remove the background-color from that.

How can I do that?


I'm not sure you can remove part of the background like you describe. Instead, your overlay can have a transparent background and it can contain four blue-ish-background div s that form a frame around the hole you want.

Here's some code that does this:

HTML:

<div id="main"/>
<div id="overlay-container">
    <div class="overlay" id="top"/>
    <div class="overlay" id="left"/>
    <div class="overlay" id="right"/>
    <div class="overlay" id="bottom"/>
</div>

CSS:

body {margin: 0; padding: 0}
#main {width: 500px; height: 200px; background: yellow;}
.overlay {background: rgba(0,0,0,0.5); position:absolute;}
#overlay-container { width: 500px; height: 200px; z-index: 99; position: absolute;}
#top {width: 100%; height: 50px}
#left {top:50px; width: 200px; height: 100px}
#right {left: 300px; width: 200px; height: 100px}
#bottom {left: -300px; top: 100px; width: 500px; height: 50px}

You can probably get rid of the overlay-container and simplify things a bit, but I don't have the imagination to do it this late at night. ;-)

EDIT

Okay, that was way too complicated. For the overlay, just use a <div> with a transparent background and a translucent border. Here's an example:

HTML:

<body>
    <div id="background">some content</div>
    <div id="overlay"></div>
</body>

CSS:

body { margin: 0; padding: 0; }
#background {
    width:500px;
    height:200px;
    background: yellow;
}
#overlay {
    border-color: rgba(0,0,0,0.5);
    border-style: solid;
    border-top-width: 50px;
    border-left-width: 200px;
    border-right-width: 200px;
    border-bottom-width: 50px;
    position: absolute;
    top: 0;
    width: 100px;
    height: 100px;
    z-index: 99;
}

You have to do something like in Ted's example. You could use JavaScript to calculate the rectangle of the element to mask and use that info to position the overlay elements.

Here is a quick example using jQuery ,

Fiddle

An alternative is to use a html canvas with the clearRect method,

Fiddle

The caveat with the canvas solution is that the canvas is overlayed over the element so it is not possible to eg. mouse select the content in the div etc.

链接地址: http://www.djcxy.com/p/69904.html

上一篇: Symfony2加载时间和性能

下一篇: 如何减少div的一部分