当前位置:主页 > 查看内容

纯CSS实现红绿灯效果(面试常见)

发布时间:2021-07-24 00:00| 位朋友查看

简介:先看题,别看答案试下吧 ~_~ 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类……

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

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;
}

总结

以上所述是小编给大家介绍的纯CSS实现红绿灯效果(面试常见),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!


原文链接:https://m.jb51.net/css/601598.html
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐