UI框架能满足部分需求,但是偶尔也需要自己手写些css与js满足一些要求。
无论是vue还是其他框架,实现table效果的本质是不变的,都是js。这里给出vue版本,其他前端同样适用
table在任何一个系统中都是会用到的,以下就是一些table的常用效果。
一,换行颜色
原生版(菜鸟上的例子):
https://www.runoob.com/try/try.php?filename=trycss_table_fancy
vue版:
vue有一个特性数据驱动,这个特性能够帮助我们少写很多的js代码并且简化流程。
换行颜色重点是区分单双行,怎么写都行,方法很多
写法一:
<template>
<div >
<table id="customers">
<tr>
<th>NAME</th>
<th>AGE</th>
<th>SA</th>
</tr>
<!-- 增加判断,奇数行样式为oddrowcolor,偶数行为evenrowcolor -->
<tr v-for="item in info" :id="trstyleflag++" :style="trstyleflag % 2 == 0 ? evenrowcolor: oddrowcolor">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sa}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: 'table',
components: {
},
data () {
return {
// 模拟后端返回数据
info : [{
name: 'gong',
age: 22,
sa: 10000
}, {
name: 'pan',
age: 22,
sa: 12000
}, {
name: 'gongpan',
age: 24,
sa: 13000
}, {
name: 'pangong',
age: 24,
sa: 13000
}, {
name: 'pg',
age: 25,
sa: 14000
}],
// 定位当前行数
trstyleflag: 1,
// 奇数样式
oddrowcolor: 'color:#000000;background-color:#EAF2D3;',
// 偶数样式
evenrowcolor: 'color:#000000;background-color:#FFFFFF;'
}
}
}
</script>
写法二:加工数据,然后用v-if, v-else
<template>
<div >
<table id="customers">
<tr>
<th>NAME</th>
<th>AGE</th>
<th>SA</th>
</tr>
<template v-for="item in info">
<tr v-if="item.odd_even_flag == 1" class="oddrowcolor">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sa}}</td>
</tr>
<tr v-else class="evenrowcolor">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sa}}</td>
</tr>
</template>
</table>
</div>
</template>
<script>
export default {
name: 'table1',
components: {
},
data () {
return {
info: null,
}
},
created() {
this.initdata()
},
methods: {
async initdata() {
let res = await this.$api.get_salary_list({})
if (res.data.code == 200) {
this.info = res.data.msg
console.log(res.data.msg)
// 为单双行填上标记
this.info.forEach( (item, index) =>{
if (index % 2 == 0 ){
item['odd_even_flag'] = 1
} else {
item['odd_even_flag'] = 0
}
})
}
}
}
}
</script>
<style>
.oddrowcolor{
color:#000000;
background-color:#EAF2D3;
}
.evenrowcolor{
color:#000000;
background-color:#FFFFFF;
}
</style>
css 如下:
<style>
#customers
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:30%;
border-collapse:collapse;
}
#customers td{
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#customers th
{
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
background: #EAF2D3;
}
</style>
二,自动滚动
自动滚动主要在js上
1,给表格添加一个父级div,固定长宽,并设置滚动样式,且父级div的长度大于子表格。
2,添加滚动js代码,并调用
// 自动滑动
Roll() {
// 获取父盒子(肯定有滚动条)
let parent = document.getElementById('parent');
// 获取table(高度肯定比父盒子大)
let table = document.getElementById('customers');
parent.scrollTop = 0
let parentheight = parent.offsetHeight
// 设置定时器,时间即为滚动速度
this.timer = setInterval(function () {
//当父级滚动高度加div本身的高度 >= table 的高度时,重新定位到顶部
if((parent.scrollTop + parentheight) >= table.scrollHeight) {
parent.scrollTop = 0;
} else {
parent.scrollTop++;
}
}, 50);
}
待更新......
附上我的微信,有问题可以问,或者一起进步。