今天收到了1个公司的面试题,其中有这么一道,做来试试。
1、页面放置一个800*600的div盒子,内部嵌入两个浮动的div!
2、随机生成一个长度为100的对象数组,数组内对象包含如下属性: width: 0-100随机数 height: 0-100随机数 top: 0-600随机数 left:0-800随机数 R: 0-255随机数 G: 0-255随机数 B: 0-255随机数 (Webqq群:795477608)
3、将第二步生成的随机数组中对象属性width大于50和小于50的对象,分别拆分到两个新的数组对象中。
4、使用一个定时器,每隔一秒执行一次,在拆分出来的两个数组中随机抽取一个对象,更改第1步中的2个浮动div的大小、位置和颜色。
(可以在jquery、vue中任意选一个框架来实现--------------代码编写过程中尽量多用ES6的新特性)
我用vue3
<template>
<div class="container">
<div class="box" :style="box1Style"></div>
<div class="box" :style="box2Style"></div>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // 随机数组
largeItems: [], // width > 50的对象数组
smallItems: [], // width <= 50的对象数组
box1Style: {}, // 第一个浮动div的样式
box2Style: {}, // 第二个浮动div的样式
};
},
created() {
this.generateRandomItems(); // 生成随机数组
this.splitItems(); // 拆分数组
setInterval(() => {
this.updateBoxStyle(); // 更新浮动div的样式
}, 1000);
},
methods: {
// 生成随机数组
generateRandomItems() {
for (let i = 0; i < 100; i++) {
const item = {
width: Math.floor(Math.random() * 101),
height: Math.floor(Math.random() * 101),
top: Math.floor(Math.random() * 601),
left: Math.floor(Math.random() * 801),
R: Math.floor(Math.random() * 256),
G: Math.floor(Math.random() * 256),
B: Math.floor(Math.random() * 256),
};
this.items.push(item);
}
},
// 拆分数组
splitItems() {
this.largeItems = this.items.filter((item) => item.width > 50);
this.smallItems = this.items.filter((item) => item.width <= 50);
},
// 更新浮动div的样式
updateBoxStyle() {
const largeIndex = Math.floor(Math.random() * this.largeItems.length);
const smallIndex = Math.floor(Math.random() * this.smallItems.length);
this.box1Style = {
width: this.largeItems[largeIndex].width + "px",
height: this.largeItems[largeIndex].height + "px",
top: this.largeItems[largeIndex].top + "px",
left: this.largeItems[largeIndex].left + "px",
backgroundColor: `rgb(${this.largeItems[largeIndex].R},${this.largeItems[largeIndex].G},${this.largeItems[largeIndex].B})`,
};
this.box2Style = {
width: this.smallItems[smallIndex].width + "px",
height: this.smallItems[smallIndex].height + "px",
top: this.smallItems[smallIndex].top + "px",
left: this.smallItems[smallIndex].left + "px",
backgroundColor: `rgb(${this.smallItems[smallIndex].R},${this.smallItems[smallIndex].G},${this.smallItems[smallIndex].B})`,
};
},
},
};
</script>
<style>
.container {
position: relative;
width: 800px;
height: 600px;
}
.box {
position: absolute;
float: left;
}
</style>