在stylus中实现random随机数功能

1,107

写在前面

与 Sass 一样,Stylus 是一门优秀的 CSS 预编译语音:富有表现力,动态,强大的CSS;

在使用 Stylus 写下面这个效果的时候,需要用到随机数,可是我翻阅了 Stylus 的文档,却没有发现可用的函数。

在这里插入图片描述

翻阅 Stylus 的文档,发现 Stylus 里面支持 JavaScript API,当有一些事情无法使用 Stylus 完成的时候,就在 JavaScript 中定义它。所以我们使用 .define(name, fn) 在 Stylus 上定义一个 random 函数。

一、如果你是直接引入的 Stylus 来编译

直接给 Stylus 扩展一个 random 函数

var stylus = require('stylus')
// 给stylus扩展一个random函数
style.define('random', function(min, max) {
	if(min === undefined || max === undefined) {
	  return Math.random()
	}
	return Math.floor(Math.random() * (Number(max) - Number(min) + 1)) + Number(min)
})

// 执行你的其他操作
// ...

二、如果你是在webpack中使用Stylus

那么根据在 webpack 中配置 stylus 的规则,我们需要将 random 函数单独写成一个 plugin。

// stylus-random.js
/*一个stylus plugin,用于生成随机数*/
module.exports = function() {
  return function(style) {
    style.define('random', function(min, max) {
      if(min === undefined || max === undefined) {
        return Math.random()
      }
      return Math.floor(Math.random() * (Number(max) - Number(min) + 1)) + Number(min)
    })
  }
}

然后在 webpack 的配置文件中引入,并根据 stylus-loader 的配置规则来使用它:

// webpack.conf.js
const stylusRandom = require('./stylus-random')
...
stylus: {
  use: [stylusRandom()]
}
...

现在呢,我们就可以在 stylus 中来使用 random 函数咯~

@keyframes ani1 {
  $indent=20
  for $index in 1..$indent {
    {$index*100/$indent + '%'} {
      clip-path: inset(random(0, 100)*1px 0 random(0, 100)*1px 0)
    }
  }
}

编译后:

@-webkit-keyframes ani1-data-v-88b5672e {
5% {
    -webkit-clip-path: inset(83px 0 75px 0);
            clip-path: inset(83px 0 75px 0);
}
10% {
    -webkit-clip-path: inset(90px 0 97px 0);
            clip-path: inset(90px 0 97px 0);
}
...
95% {
    -webkit-clip-path: inset(91px 0 61px 0);
            clip-path: inset(91px 0 61px 0);
}
100% {
    -webkit-clip-path: inset(15px 0 98px 0);
            clip-path: inset(15px 0 98px 0);
}
}
@keyframes ani1-data-v-88b5672e {
5% {
    -webkit-clip-path: inset(83px 0 75px 0);
            clip-path: inset(83px 0 75px 0);
}
10% {
    -webkit-clip-path: inset(90px 0 97px 0);
            clip-path: inset(90px 0 97px 0);
}
...
95% {
    -webkit-clip-path: inset(91px 0 61px 0);
            clip-path: inset(91px 0 61px 0);
}
100% {
    -webkit-clip-path: inset(15px 0 98px 0);
            clip-path: inset(15px 0 98px 0);
}
}

文中截图的css效果来自:neveryu.github.io/web-bookmar…

参考资料

Stylus 中文文档

张鑫旭 stylus中文版参考文档

stylus-loader


写在最后

我的主页: neveryu.github.io/index.html

QQ群:685486827832485817