javascript - 是否可以使用 html/javascript/css 在 img 元素中打洞?

标签 javascript html css

我正在开发一个网站,其背景部分需要透明,因为其背后的视频需要通过。背景是图像。另外,我需要确保该网站在 Opera 版本 11 上运行。

考虑到网站需要在 Opera 11 浏览器中运行,有没有办法在图像元素上挖一个洞? <img src='http://ip/cutaholeinme.png'>

所以最后,下面的image with a hole被展示; (白色矩形应该是透明的)

enter image description here

最佳答案

掩模可以轻松做到这一点

img {
  -webkit-mask:
    linear-gradient(#fff,#fff) top   / 100% 50px, /* show 50px from the top */
    linear-gradient(#fff,#fff) bottom/ 100% 70px, /* show 70px from the bottom */
    linear-gradient(#fff,#fff) left  / 20% 100%,  /* show 20% from the left */
    linear-gradient(#fff,#fff) right / 40% 100%;  /* show 40% from the right */
  -webkit-mask-repeat:no-repeat;
  
  mask:
    linear-gradient(#fff,#fff) top   / 100% 50px,
    linear-gradient(#fff,#fff) bottom/ 100% 70px,
    linear-gradient(#fff,#fff) left  / 20px 100%,
    linear-gradient(#fff,#fff) right / 40px 100%;
  mask-repeat:no-repeat;
}

body {
 background:linear-gradient(to right,blue,red);
}
<img src="https://picsum.photos/id/1006/500/400" >

为了获得更好的支持,您可以考虑使用 SVG mask :How to apply background to specific elements only?

<小时/>

您还可以考虑使用多个元素的技巧,如下所示:

.box {
  width: 500px;
  height: 400px;
  position: relative;
  background-size: 0 0;
}

.box div {
  background: inherit;
  height: 100%;
}

.box:before,
.box:after,
.box div:before,
.box div:after {
  content: "";
  position: absolute;
  background-image: inherit;
  background-size: 500px 400px;
}

.box:before,
.box:after {
  left: 0;
  right: 0;
}

.box:before {
  top: 0;
  background-position:top;
  height: 20%;
}

.box:after {
  bottom: 0;
  background-position:bottom;
  height: 30%;
}

.box div:before,
.box div:after {
  top: 0;
  bottom: 0;
}

.box div:before {
  left: 0;
  background-position:left;
  width: 40px;
}

.box div:after {
  right: 0;
  background-position:right;
  width: 80px;
}

body {
  background: linear-gradient(to right, blue, red);
}
<div class="box" style="background-image:url(https://picsum.photos/id/1006/500/400)">
  <div></div>
</div>

关于javascript - 是否可以使用 html/javascript/css 在 img 元素中打洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564183/

相关文章:

javascript - 在 Javascript 中循环音频直到警报解除

javascript - jQuery 以编程方式触发事件

javascript - 从 Bootstrap 导航栏滚动到元素

html - CSS 百分比栏采用 100% 而不是 40%

javascript - 过滤键的最佳方法

javascript - 如何使用 Javascript 中的字符串来验证两个单独的 JSON 字典中的数据?

javascript - 如何动态添加表格行,包括文本框和具有不同 ID 的选择框

html - 为什么我不能在标题中缩放此图像?

html - 修复滚动时隐藏在其他 div 后面的 div

javascript - 仅在 Safari 中加载后 Google Maps API 修改页面样式