这个是昨天晚上看电视里面有个抽奖效果,看起来觉得有点意思,就自己写了下,暂时就叫他随机排序抽奖吧。其实原理也没啥,就是随机修改位置,点击的时候,覆盖css就可以了,具体看下面的演示:
1号
2号
3号
4号
5号
6号
7号
8号
9号
10号
11号
12号
13号
14号
15号
16号
17号
18号
19号
20号
21号
22号
23号
24号
25号
26号
27号
28号
下面是css部分:
- .div {
- width: 100px;
- height: 100px;
- background: #fff;
- position: absolute;
- left: 0;
- top: 0;
- border: 1px solid #222;
- transition: all 0.4s ease;
- -moz-transition: all 0.4s ease;
- -webkit-transition: all 0.4s ease;
- cursor: pointer;
- z-index: 2;
- text-align: center;
- line-height: 100px;
- }
- .div span {
- opacity: 0;
- transition: all 0.4s ease;
- -moz-transition: all 0.4s ease;
- -webkit-transition: all 0.4s ease;
- }
- .bg {
- width: 100%;
- height: 100%;
- background: #000;
- position: fixed;
- left: 0px;
- top: 0px;
- opacity: 0;
- transition: all 0.4s ease;
- -moz-transition: all 0.4s ease;
- -webkit-transition: all 0.4s ease;
- }
- .div img {
- opacity: 0
- }
- button {
- display: block;
- width: 200px;
- line-height: 40px;
- background: blue;
- color: #fff;
- border: none;
- margin: 10px auto;
- position: relative;
- z-index: 21;
- font-size: 20px;
- }
- .div.show {
- z-index: 18 !important;
- transform: perspective(800px) translate3d(-50%, -50%, 0px) rotateY(180deg) scale(-2, 2) !important;
- -moz-transform: perspective(800px) translate3d(-50%, -50%, 0px) rotateY(180deg) scale(-2, 2) !important;
- -webkit-transform: perspective(800px) translate3d(-50%, -50%, 0px) rotateY(180deg) scale(-2, 2) !important;
- left: 50% !important;
- top: 50% !important;
- }
- .div.show span {
- opacity: 1
- }
- .bg.show {
- opacity: 0.4;
- z-index: 8
- }
下面是js部分:
- var div = document.querySelectorAll(‘.div’); //元素
- var bg = document.querySelector(‘.bg’); //背景
- var btn = document.querySelector(‘button’); //按钮
- function Random(s,e){return Math.random()*(e-s)+s;}; //随机函数
- var n = null; //保存点击元素的序号
- //初始化
- function init(){
- [].forEach.call(div,function(o,i){
- o.off = true; //给每个元素添加开关,阻止多次点击
- o.classList.remove(‘show’); //删除class
- bg.classList.remove(‘show’); //删除class
- //添加css
- o.style.transform = o.style.MozTransform = o.style.WebkitTransform = ‘translate3d(‘+Random(0,document.documentElement.clientWidth – o.offsetWidth)+’px,’+Random(0,document.documentElement.clientHeight – o.offsetHeight)+’px,0px) rotate(‘+(Random(-360,360))+’deg)’;
- //点击事件
- o.onclick = function(){
- //判断开关
- if(this.off){
- n = i; //保存序号
- this.classList.add(‘show’); //添加class
- bg.classList.add(‘show’);//添加class
- this.off = false; //关闭开关
- };
- };
- });
- };
- //背景点击事件
- bg.onclick = function(){
- if(!n) return
- div[n].off = true;
- div[n].classList.remove(‘show’)
- this.classList.remove(‘show’)
- }
- init();
- window.addEventListener(‘resize’,init,false);
- btn.onclick = init