如何在具有黑色背景颜色的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>
在
在
答案 0 :(得分:4)
这里的问题是,即使你这样做,你只是会看到你的透明的半黑色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>
希望这有帮助。
奖励:使用类似的东西将.b附加到鼠标:
$(document).on('mousemove', function(e){
$('.b').css({
left: e.pageX -25,
top: e.pageY -25
});
});
答案 1 :(得分:1)
对于JavaScript解决方案,请查看此jsFiddle:little link。
如果代码的任何部分含糊不清,我很乐意解释它。请注意,我尝试过一点改进HTML和CSS结构 - 不再需要指定width
或height
s。
以下是代码的注释版本,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
希望有所帮助!