面试题之纯css实现红绿灯效果(ps:真的很纯)

先看题,别看答案试下吧 ~_~

1、下面的代码输出的内容是什么?

function O(name){
    this.name=name||'world';
}
O.prototype.hello=function(){
    return function(){
        console.log('hello '+this.name)
    }
}
var o=new O;
var hello=o.hello();
hello();
复制代码
分析:
    1、O类实例化的时候赋值了一个属性name,默认值为world,那么在实例化的时候并未给值,所以name属性为world
    2、O类有一个原型方法hello,该方法其实是一个高阶函数,返回一个低阶函数,精髓就在这个低阶函数中的this,
        注意这里的低阶函数其实是在window环境中运行,所以this应该指向的是window
复制代码

所以我的答案是:'hello undefined'(但这个答案是错误的,哈哈)

圈套:殊不知原生window是有name属性的,默认值为空
复制代码

所以正确答案应该是:hello

2、给你一个div,用纯css写出一个红绿灯效果,按照红黄绿顺序依次循环点亮(无限循环)

  • 当时没写出来,现场手写这么多代码是有难度的,下面是我后面实现代码(省略了浏览器兼容性前缀)

<div id="lamp"></div>

复制代码

/*
思路:
    总共三个灯,分别红黄绿,要一个一个按顺序点亮,我们可以这样暂定一个循环需要10秒中,每盏灯点亮3秒,
    那么在keyframes中对应写法就如下所示(红灯点亮时间为10%--40%,黄灯点亮时间为40%--70%,绿灯点亮时间为70%--100%)
*/

@keyframes redLamp{
    0%{background-color: #999;}
    9.9%{background-color: #999;}
    10%{background-color: red;}
    40%{background-color: red;}
    40.1%{background-color: #999;}
    100%{background-color: #999;}
}
@keyframes yellowLamp{
    0%{background-color: #999;}
    39.9%{background-color: #999;}
    40%{background-color: yellow;}
    70%{background-color: yellow;}
    70.1%{background-color: #999;}
    100%{background-color: #999;}
}
@keyframes greenLamp{
    0%{background-color: #999;}
    69.9%{background-color: #999;}
    70%{background-color: green;}
    100%{background-color: green;}
}
#lamp,#lamp:before,#lamp:after{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #999;
    position: relative;
}
#lamp{
    left: 100px;
    animation: yellowLamp 10s ease infinite;
}
#lamp:before{
    display: block;
    content: '';
    left: -100px;
    animation: redLamp 10s ease infinite;
}
#lamp:after{
    display: block;
    content: '';
    left: 100px;
    top: -100px;
    animation: greenLamp 10s ease infinite;
}
复制代码
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值