您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

面试题 CSS 实现红绿灯效果

时间:12-14来源:作者:点击数:
城东书院 www.cdsy.xyz

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 写出一个红绿灯效果,按照红黄绿顺序依次循环点亮(无限循环)

  • 当时没写出来,现场手写这么多代码是有难度的,下面是我后面实现代码(省略了浏览器兼容性前缀)
@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;
}

在线示例:https://www.cdsy.xyz/tools/runcode?name=traffic_light_example

城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐