當前位置:
首頁 >
前端技术
> 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;}} }?
總結
- 上一篇: 讲几个关于程序员笑话!
- 下一篇: 短视频发展高峰论坛召开 爱奇艺号开放打通