当前位置:
首页 >
前端技术
> javascript
>内容正文
javascript
纯JS实现课表
一、需求描述
如下图所示:
实现一个课表,对应现实生活中对的课表:一门课一天内,可以对应多个节次。
二、实现思路及代码
2.1实现思路:
flex布局+position
分两步:1、先画出一个空课表;2、在正确的位置上显示课程名称
2.2数据结构
数据中需要包含:课程名称(course)、对应周几(week)、对应的开始节次(startSection)、结束节次(endSection),如下
const data = [{week:1,startSection:1,endSection:2,course:'语文'},{week:1,startSection:10,endSection:12,course:'化学'},{week:3,startSection:1,endSection:4,course:'大学物理'},{week:4,startSection:5,endSection:6,course:'English'}, ]2.3实现代码:
js代码:
包括两部分:
空课表:flex布局+css3中的 nth-of-type;
填充课程:外层-relative,内层-absolute,两个div重叠后,通过left和top让课程的div刚好贴到课表的内容区域,再通过left和top设置每个课程的位置,具体如下:
top:(课程开始节次-1)*空课表中每个“div”的高度;
left:(课程周次-1)*空课表中每个“div”的宽度;
height:(课程开始节次-结束节次+1)**空课表中每个“div”的高度;(line-height和height一样,可使垂直居中)
/*** @name: Simple* @author: wangjiao* @description:极简版本*/ import React from 'react'; import styles from './simple.less';const sections = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((i) => `第${i}节`); const weeks = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => `周${i}`);const data = [{week:1,startSection:1,endSection:2,course:'语文'},{week:1,startSection:10,endSection:12,course:'化学'},{week:3,startSection:1,endSection:4,course:'大学物理'},{week:4,startSection:5,endSection:6,course:'English'}, ] const Simple: React.FC<{}> = props => {return (<div className={styles.root}>{/*空课程表前端代码*/}<div className={styles.content}><div className={styles.rowHead}>{weeks.map((item, index) => {if (index === 0) {return (<div className={styles.empty} />)}return (<div className={styles.headItem}>{item}</div>)})}</div>{sections.map((rowItem, i) => <div className={styles.rowItem}>{weeks.map((columnItem, j) => {if (j === 0) {return <div className={styles.columnHead}>{rowItem}</div>}return <div className={styles.columnItem}/>})}</div>)}</div>{/*课程名称代码*/}<div className={styles.topContent}>{data.map((item)=>{return<div className={styles.item} style={{top:`${(item.startSection-1)*52}px`,left:`${(item.week-1)*100}px`,height:`${(item.endSection-item.startSection+1)*52}px`,lineHeight:`${(item.endSection-item.startSection+1)*52}px`}} >{item.course}</div>})}</div></div>) }; export default Simple;less代码:
.root{width:780px;margin: 0 auto;background-color: white;position: relative;.content{width: 100%;display: flex;flex-direction: column;font-size:14px;font-weight:400;color:rgba(59,66,107,1);&>div:nth-of-type(even){background:rgba(244,247,253,1);}.rowHead{height:68px ;line-height:68px ;display: flex;.empty{width: 80px;}.headItem{width: 100px;text-align: center;}}.rowItem{height: 52px;line-height: 52px;display: flex;.columnHead{width: 80px;text-align: center;}.columnItem{width: 100px;border-left: 1px solid #E6E8FB;text-align: center;}}}.topContent{position: absolute;top:68px;left: 80px;width: 700px;height: 80px;.item{width: 100px;text-align: center;position: absolute;background-color: white;border: 1px solid #E6E8FB;}} }总结
- 上一篇: 讲几个关于程序员笑话!
- 下一篇: 汇编 跳转指令: JMP、JCXZ、JE