CSS溢出时如何添加透明图像遮罩

5

我正在尝试实现一个类似于CSS属性的效果:“overflow: transparent 50%”。例如,如果我有以下内容:

<div style="border: 1px solid black; width: 200px; height: 200px; overflow: visible;">
 <img src="img.png">
</div>

我希望在200x200的框中显示图像的部分是正常的。我想让超出200x200框的图像部分变得半透明。也许可以通过在主div周围定义四个div来实现这一点?我不确定有没有简单的方法来做到这一点。

+------------------+
| img overflow,    |
| 50% transparent  |
|  +------------+  |
|  | normal img |  |
|  +------------+  |
|                  |
+------------------+

图片的宽度和高度在事先已知。该div将附有一些javascript,以允许通过拖动重新定位图像,因此div将表现为一个视口,图像可能会在任何一侧溢出。理想情况下需要在所有浏览器中工作。


通常情况下,溢出会将内容的额外部分推到容器的右侧和底部。您是否希望将其均匀地推向4个方向?(如您的图表所示) - vantrung -cuncon
你事先知道图像的宽度/高度吗,还是“未知”的?你需要支持哪些浏览器? - thirtydot
图片的宽度和高度事先已知。DIV元素将附带一些JavaScript代码,以允许通过拖动重新定位图像,因此DIV元素将充当视口,并且图像可能会在任何一侧溢出。理想情况下需要在所有浏览器中都能正常工作。 - mjibson
1个回答

2

不确定浏览器支持程度如何,但是类似这样的东西应该可以让你开始:

 <style>
     /* .container needs to be same size at img */
     .container {width:400px; height:400px; background:#00f; opacity:0.5; margin:0 auto; position:relative; z-index:1;}
     /* .container:before 1/4 img width, 1/2 img height, left 0, top 1/4 img, */
     .container:before {content:""; display:block; width:100px; height:200px; position:absolute; left:0px; top:100px; z-index:15; background:#0f0; opacity:0.5;}
     /* .container:before 1/4 img width, 1/2 img height, left 3/4 img, top 1/4 img */
     .container:after {content:""; display:block; width:100px; height:200px; position:absolute; left:300px; top:100px; z-index:15; background:#0f0; opacity:0.5;}
     /* .img would be your actual img at full size */
     .img {display:block; width:400px; height:400px; position:absolute; z-index:10; background:#f00;}
     /* .img:before same width as img, 1/4 height, top 0, left 0 */
     .img:before {content:""; display:block; width:400px; height:100px; position:absolute; left:0px; top:0px; z-index:15; background:#00f; opacity:0.5;}
     /* .img:after same width as img, 1/4 height, top 3/4 img height, left 0 */
     .img:after {content:""; display:block; width:400px; height:100px; position:absolute; left:0px; top:300px; z-index:15; background:#00f; opacity:0.5;}
 </style>
 <div class="container">
   <span class="img"></span>
 </div>

编辑:忘记了JS Fiddle链接。 http://jsfiddle.net/BradleyStaples/rWzng/

该链接是一个JS Fiddle,你可以在这里查看和编辑代码。

但是,**.container** 的不透明度需要设置为1,对吗? - Adam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接