2

如何在具有黑色背景色的 div 上制作具有透明背景色的特定 div?

谢谢。

我试图让它与添加另一个透明但没有运气的 div 一起工作,我的代码如下

.a {
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
}

.b {
    opacity: 0.7;
    background-color: #000;
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
}

.c {
    opacity: 1;
    position: absolute;
    top: 120px;
    left: 170px;
    width: 100px;
    height: 30px;
    background-color: transparent;
}​

<div class="a"><img src="http://www.helpinghomelesscats.com/images/cat1.jpg" /></div>
<div class="b"></div>
<div class="c"></div>

http://jsfiddle.net/sJW6U/1/

在此处输入图像描述

在此处输入图像描述

4

2 回答 2

4

这里的问题是,即使你这样做,你只会看到你的透明 div 后面的半黑色 div,它不会“切掉”它下面的 div。

那这个呢?

.a {
    width: 300px;
    height: 300px;
    position: absolute;
    cursor: none;
    top: 0;
    left: 0;
    /*overflow hidden to contain box shadow*/
    overflow: hidden;
}

.b {
    position: absolute;
    /*using box-shadow to create background*/
    -webkit-box-shadow: 0 0 0 50000px rgba(0,0,0,0.7);
    box-shadow: 0 0 0 50000px rgba(0,0,0,0.7);
    /*change height and position as needed*/
    width: 50px;
    height: 50px;
    top: 45px;
    left: 75px;
    z-index: 10;
}​

标记必须更改为以下内容:

 <div class="a">
    <img src="http://www.helpinghomelesscats.com/images/cat1.jpg" />
    <div class="b"></div>
</div>

http://jsfiddle.net/sJW6U/71/

希望这可以帮助。

奖励:使用这样的东西将 .b 附加到鼠标:

$(document).on('mousemove', function(e){
    $('.b').css({
       left:  e.pageX -25,
       top:   e.pageY -25
    });
});
于 2012-11-26T09:46:32.473 回答
1

对于 JavaScript 解决方案,请查看这个 jsFiddle:little link

如果代码的任何部分含糊不清,我很乐意解释。请注意,我已尝试稍微改进您的 HTML 和 CSS 结构——不再需要指定widths 或heights 。

以下是代码的注释版本,HTML:

<div class = "a">
    <img src = "http://www.fox.com/glee/_ugc/images/bios/jayma-mays_small.jpg"/>
    <div class = "b">
    </div>
    <div class = "c">
    </div>
</div>​

CSS:

.a {
    position: relative; /*to make sure children are positioned relatively to it*/
    top: 0;
    left: 0;
    display: inline-block;
}
.b {
    opacity: 0.7;
    background-color: #000;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0; /*fill all of the parent*/
    z-index: 5;
}
.c {
    position: absolute;
    z-index: 10;
}​

JavaScript:

function clip(x1, y1, x2, y2) {
    var w = x2 - x1, h = y2 - y1; //find width and height of the clipping area
    var div = document.getElementsByClassName("c")[0];
    div.style.backgroundImage = "url('http://www.fox.com/glee/_ugc/images/bios/jayma-mays_small.jpg')";
    div.style.backgroundPosition = (-x1) + "px " + (-y1) + "px";
    div.style.width = w + "px";
    div.style.height = h + "px";
    div.style.top = y1 + "px";
    div.style.left = x1 + "px";
}
clip(75, 75, 150, 150); //clips from 75, 75 to 150, 150, you can customize it

希望有帮助!

于 2012-11-26T09:52:32.840 回答