从酷炫的果冻菜单谈起 CSS3 filter 属性

原文链接: github.com

从酷炫的果冻菜单谈起 CSS3 filter 属性

今天中午刷掘金沸点时,看到一个 Jerry Menu,看着效果不错,就像学(抄)习(袭)一下。效果图见下:

jerrymenu效果图

这里我要学(抄)习(袭)的就是这个菜单效果,这个 dom 结构还是很简单的。

div.blobs
    div.circle.main
    div.circle.sub.first
    div.circle.sub.second
    div.circle.sub.last

用CSS美化一下:

.blobs {
	display: flex;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
}

.circle {
	position: absolute;
	width: 90px;
	height: 90px;
	transform: translate(0, -48px);
	background: hsl(337, 70%, 58%);
	clip-path: circle(42px at center);
}

.circle.main {
    z-index: 2;
}

为了更直接到达目标效果,先不做动画,先把各个菜单的位置写好:

.first {
	transform: translate(-100px, -120px);
	background: hsl(307, 70%, 58%);
}

.second {
    transform: translate(0px, -150px);
	background: hsl(277, 70%, 58%);
}

.last {
    transform: translate(100px, -120px);
	background: hsl(247, 70%, 58%);
}

这时候效果就出来了,大致长这样:

image

最开始的效果是有交互的,那我们就用JS加一点交互:

const button = document.querySelector(".circle.main");
const circles = document.querySelectorAll(".circle.sub");

button.addEventListener("click", function() {
  circles.forEach(element => {
    element.classList.toggle("show");
  });
});

相应地,CSS也要作出变更:

.first {
	transition: transform 0.5s 100ms ease-out;
	background: hsl(307, 70%, 58%);
}

.second {
	transition: transform 0.5s 300ms ease-out;
	background: hsl(277, 70%, 58%);
}

.last {
	transition: transform 0.5s 500ms ease-out;
	background: hsl(247, 70%, 58%);
}

.first.show {
	transform: translate(-100px, -120px);
}

.second.show {
	transform: translate(0px, -150px);
}

.last.show {
	transform: translate(100px, -120px);
}

这时候效果就差不多了:

jerrymenu_0

但是总感觉差了点什么,粘连效果没了,看一下原作者的效果:

jerrymenu效果图

赶紧回头看下了作者的源代码,发现作者加了 .blobs { filter: url(#goo); } 这样的滤镜效果,翻看文档看了下:

CSS滤镜属性,可以在元素呈现之前,为元素的渲染提供一些效果,如模糊、颜色转移之类的。滤镜常用于调整图像、背景、边框的渲染。SVG滤镜资源(SVG Filter Sources)是指以xml文件格式定义的svg滤镜效果集,可以通过URL引入并且通过锚点(#element-id)指定具体的一个滤镜元素。

再设置 filter 滤镜并加上相应的 svg 代码之后,整个 Jerry Menu 的效果就学(抄)习(袭)完了,效果如下:

jerrymenu_1

这里附上 MDN上关于 filter 的文档