filter()實現模糊的三種方式

2018/4/23 陰天


filter:blur(2px) 是實現背景模糊的主要屬性,下面來講述filter實現三種效果的方法。
blur裏的參數是設定高斯函數的標準差,或者說是屏幕上以多少像素融在一起,所以值越大,越模糊。

1 普通背景模糊

filter屬性會使整個div的後代模糊並且還會出現白邊,如果想讓div裏的子元素不模糊,,怎麼辦呢?可以使用僞元素,既解決了模糊問題,也解決了白邊問題。

  • 實現思路:
    在父容器中設置背景,並且使用相對定位,方便僞元素重疊;在:after中只需要繼承背景,並且設置模糊,絕對定位覆蓋父元素即可,這樣父容器中的子元素便可不受模糊度影響。因爲僞元素的模糊度不能被父元素的子代繼承。

  • 代碼如下:

html
<div class="bg">
  <div class="drag">like window</div>
</div>

css
.bg{
  with:100%;
  hight:100%;
  position:relative;
  background:url("picture") no-repeat fixed;
  padding:1px;
  box-sizing:border-box;
  z-index:1;
}
.bg:after{
  content:"";
  width:100%;
  height:100%;
  position:absolute;
  left:0;
  top:0;
  background:inherit;
  filter:blur(2px);
  z-index:2;
}
.drag{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
width:200px;
height:200px;
text-align:center;
z-index:11;
}

這裏需要注意三個地方:
1 子代元素也需要使用絕對定位
2 需要用z-index確定層級關係
3 保證子代元素的層級最高

1 背景局部模糊

背景局部模糊不需要設置父元素的僞元素爲模糊,直接在你想模糊的元素外面套一個div,給該元素的僞元素模糊即可。

html部分
<div class="bg">
  <div class="drag">
    <div>like window</div>
  </div>
</div>
css部分
.bg{
width:100%;
height:100%;
background:url("picture") no-repeat fixed;
padding:1px;
box-sizing:border-box;
z-index:1;
}
.drag{
margin:100px auto;
width:200px;
height:200px;
background:inherit;
position:relative;
}
.drag >div{
width:100%;
height:100%;
text-align:center;
line-height:200px;
position:absolute;
left:0;
top:0;
z-index:11;
設置子元素的層級高一些,不會被drag覆蓋
}
.drag:after{
content:"";
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
background:inherit;
filter:blur(15px);
z-index:2;
}

1 背景局部模糊

設置父元素的僞元素的filter,子元素的z-index高於父元素。

.bg{
width:100%;
height:100%;
position:relative;
background:url(picture) no-repeat fixed;
padding:1px;
box-sizing:border-box;
}
.bg:after{
content:"";
width:100%;
height:100%;
position:absolute;
left:0;
top:0;
background:inherit;
filter:blur(3px);
z-index:1;
}
.drag{
position:absolute;
left:40%;
top:30%;
width:200px;
height:200px;
text-align:center;
background:inherit;
z-index:11;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章