JS面向对象——利用transform实现扇子效果
效果:
实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> .fan { margin: 0 auto; position: relative; top: 100px; width: 50px;} .fan-other { margin: 0 auto; position: relative; top: 300px; width: 50px;} </style> <body> <div></div> <div></div> <script> (function(){ // 扇子类 class Fan { // Fan类的构造器,接收传入的参数 // params selector 容器的选择器 // params options 一些配置参数 // options size 尺寸 // ... // void return constructor ( selector, options ) { // 扇子容器 this.selector = selector this.wrapper = document.querySelector(selector) // 默认配置项 let _options = { size: 'normal' // large } // 配置项 this.options = options || _options // 扇叶的尺寸 this.size = { width: 50, height: 150 } // 进行初始化操作 this.init() } // 初始化函数 init () { // 创建扇叶 this.createFanBlade() } // 创建扇叶 createFanBlade () { // 扇叶的数量 当new时size不为normal时,输出11片扇叶的扇子 let _bladeNumbers = this.options.size === 'normal' ? 9 : 11; let _fragmentStr = ''; let { width, height } = this.size; // 扇叶样式 let _bladeStyle = { width: width + 'px', height: height+ 'px', position: 'absolute', top: 0, left: 0 } for (let i = 0; i < _bladeNumbers; i++) { _bladeStyle.background = this.createRandomColor()//背景颜色随机 _fragmentStr += `<div></div>` } // 放入扇叶 this.wrapper.innerHTML = _fragmentStr ; this.createTransition(_bladeNumbers); } // 制作动效Style并插入到head中 createTransition (_bladeNumbers) { let _result = '<style>'; _result += ` ${this.selector} div { transition: all 0.5s; transform-origin: center bottom; } `; // 0 1 2 3 4 5 6 7 8 角度转化 0-8 中间是0° -70°~70° for (let i = 0; i < _bladeNumbers; i++) { let _num = (_bladeNumbers - 1) / 2 let _angle = (i - _num) * 70 / _num _result += ` ${this.selector}:hover div:nth-child(${i+1}){ transform: rotate(${_angle}deg); } ` } _result += '</style>' document.querySelector('head').innerHTML += _result; } // 转换样式对象为字符串 turnStyleToString (styleObject) { let _result = '' for (const key in styleObject) { _result += key + ':' + styleObject[key] + ';' } return _result; } // 随机创建颜色 createRandomColor () { return "#"+(function(color){ return new Array(7-color.length).join("0")+color; })((Math.random() * 0x1000000 | 0).toString(16)); } } new Fan('.fan') new Fan('.fan-other', { size: 'large' }) })(); </script> </body> </html>