我有一个JPEG文件,我使用作为搜索页面的背景图像,我使用CSS来设置它,因为我在Backbone.js上下文中工作:

background-image: url("whatever.jpg");

我想应用css3模糊过滤器只对背景,但我不确定如何样式只是一个元素。如果我试着:

-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);

就在我的CSS中的background-image下面,它为整个页面设置了样式,而不仅仅是背景。是否有一种方法只选择图像并应用过滤器?或者,有没有一种方法可以关闭页面上所有其他元素的模糊效果?


当前回答

当然,这不是css解决方案,但你可以使用CDN质子过滤器:

body {
    background: url('https://i0.wp.com/IMAGEURL?w=600&filter=blurgaussian&smooth=1');
}

它来自https://developer.wordpress.com/docs/photon/api/#filter

其他回答

我没有写这个,但是我注意到使用CSS SASS编译器有一个部分支持的后台过滤器的polyfill,所以如果你有一个编译管道,它可以很好地实现(它也使用TypeScript):

https://codepen.io/mixal_bl4/pen/EwPMWo

下面是一个简单的解决方案,适用于现代浏览器,使用纯CSS和一个'before'伪元素,就像Matthew Wilcoxson的解决方案一样。

为了避免在JavaScript中需要访问伪元素来更改图像和其他属性,只需使用inherit作为值,并通过父元素(这里是body)访问它们。

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);
}

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */
}

成功应用背景图像的步骤

确保使用link标签正确链接了HTML和CSS <link rel="stylesheet" ref="yourcssdocument.css"> 我不知道相对目录和子目录,所以我不能评论它 对我来说,最好的方法是在css中使用URL链接

#yourcssdoc .image {
   background-image: url("paste your link here with the quotations")
}

如果你想要内容是可滚动的,设置内容的位置为绝对:

content {
   position: absolute;
   ...
}

我不知道这是不是只适合我,但如果不是,这就是解决办法!

此外,由于背景是固定的,这意味着你有一个“视差”效果!所以现在,这个人不仅教你如何制作一个模糊的背景,而且它也是一个视差背景效果!

正如在其他答案中所述,这可以通过以下方式实现:

作为背景的模糊图像的副本。 可以过滤的伪元素,然后将其定位在内容后面。

你也可以使用backdrop-filter

有一个受支持的属性叫做backdrop-filter,目前是 支持Chrome, Firefox, Edge, Safari和iOS Safari(查看caniuse.com统计数据)。

来自Mozilla devdocs:

backdrop-filter属性提供了一些效果,比如对元素后面的区域进行模糊或颜色移动,然后通过调整元素的透明度/不透明度就可以看到元素。

查看caniuse.com了解使用统计数据。

你会这样使用它。 如果你不想让里面的内容被模糊化,使用实用工具类.u-non- ambiguous

.background-filter::after { -webkit-backdrop-filter: blur(5px); /* Use for Safari 9+, Edge 17+ (not a mistake) and iOS Safari 9.2+ */ backdrop-filter: blur(5px); /* Supported in Chrome 76 */ content: ""; display: block; position: absolute; width: 100%; height: 100%; top: 0; } .background-filter { position: relative; } .background { background-image: url('https://upload.wikimedia.org/wikipedia/en/6/62/Kermit_the_Frog.jpg'); width: 200px; height: 200px; } /* Use for content that should not be blurred */ .u-non-blurred { position: relative; z-index: 1; } <div class="background background-filter"></div> <div class="background background-filter"> <h1 class="u-non-blurred">Kermit D. Frog</h1> </div>