黑白格子触动效果制作(内附完整代码+stylus转css教程)

265 阅读3分钟

前言

你是否想做一个如视频所示的,鼠标触摸后格子会缓慢变大的黑白格子块,接下来我将用不一样的css编写方法,带领你完成这个项目。

代码实现

html代码

html代码部分则是用熟悉的ul父元素和子元素们来布局,元素样式则是导入common.css链接。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手风琴</title>
    <link rel="stylesheet" href="common.css">
</head>
<body>
    <ul class="check">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>
</body>
</html>

css代码

首先,这里教大家一个更高级更便利敲css代码,那就是用styl来编写css,接下来我将演示如何用styl来编写css。首先认识一下什么是stylus。

什么是stylus?

Stylus 是一种 CSS 的预处理器,它扩展了 CSS 的功能,使得编写 CSS 更加灵活和高效。Stylus 提供了诸如变量、嵌套规则、运算符、函数、混入(mixins)、迭代器以及其他编程特性,让 CSS 编写起来更像是一种编程语言。通过这些增强功能,开发者可以更方便地组织和维护 CSS 代码,减少重复,提高开发效率,并且易于实现代码的模块化和可重用性。

接下来,我们来编写common.styl

common.styl

  • 首先先安装stylus的包
    • 打开终端并运行以下命令 npm install -g stylus
  • 在目录下创建一个common.styl文件
  • 开始编写common.styl
*
    margin 0
    padding 0
    box-sizing: border-box
ul, li
    list-style none

.check
    display flex
    width 600px
    height 200px
    li  
        flex 1
        cursor pointer
        line-height 200px
        text-align center
        transition flex 500ms
        &:nth-child(1)
            background-color white
        &:nth-child(2)
            background-color black
            color white
        &:nth-child(3)
            background-color white
        &:nth-child(4)
            background-color black
            color white
        &:nth-child(5)
            background-color white
        &:nth-child(6)
            background-color black
            color white
        &:hover
            flex 2
  • 在终端输入stylus common.styl -o common.css实现stylus编译,也可以先在终端输入stylus -w common.styl -o common.css,实现边编写,边编译的功能
  • 可以输入stylus进行搜索插件安装,来帮助编写stylus

stylus编写css的优点:

  • stylus不需要写大括号 {} 或分号 ; 来界定代码块,取而代之的是tab 缩进;
  • Stylus允许使用变量、嵌套、运算符、函数等,如上述中的&:checked:nth-child中,&代表上级标签;
  • Stylus 允许 CSS 规则嵌套;
  • 装B(想象一下面试官要你写一个css,你用stylus一顿天花乱坠,直接遥遥领先!)。

编译后的common.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
ul,
li {
  list-style: none;
}
.check {
  display: flex;
  width: 600px;
  height: 200px;
}
.check li {
  flex: 1;
  cursor: pointer;
  line-height: 200px;
  text-align: center;
  transition: flex 500ms;
}
.check li:nth-child(1) {
  background-color: #fff;
}
.check li:nth-child(2) {
  background-color: #000;
  color: #fff;
}
.check li:nth-child(3) {
  background-color: #fff;
}
.check li:nth-child(4) {
  background-color: #000;
  color: #fff;
}
.check li:nth-child(5) {
  background-color: #fff;
}
.check li:nth-child(6) {
  background-color: #000;
  color: #fff;
}
.check li:hover {
  flex: 2;
}

在css中,我们使用了弹性布局来更加灵活地排列和对齐项目,调整了flex属性,实现良好的响应式布局。并且通过设置transition flex 500ms来实现鼠标触摸后格子的缓慢变大。