当我向右滚动表格时,我想冻结表格中的列。 我是使用js静态完成的,但是在这种情况下是否有办法指示列数以获得以下样式?
我的js代码看起来是这样的:
var styles =`
table:first-of-type thead tr th:first-child{
position: sticky;
position: -webkit-sticky;
background-color:white;
color:crimson;
left: 0px;
z-index: 3;
}
table:first-of-type tbody tr td:first-child{
position: sticky;
position: -webkit-sticky;
background: crimson;
left: 0px;
color:black;
z-index: 1;
}
table:first-of-type thead tr th:nth-child(2){
position: sticky;
position: -webkit-sticky;
color: black;
left: 30px;
z-index: 3;
}
table:first-of-type tbody tr td:nth-child(2){
position: sticky;
position: -webkit-sticky;
background: black;
left: 30px;
z-index: 1;
}
table:first-of-type thead tr th:nth-child(3){
position: sticky;
position: -webkit-sticky;
color: black;
left: 138px;
z-index: 3;
}
table:first-of-type tbody tr td:nth-child(3){
position: sticky;
position: -webkit-sticky;
background: black;
left: 138px;
z-index: 1;
}
`;
var styleSheet = document.createElement("style")
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
在这种情况下,我每次都必须添加 nth-child,但是可以用 js 函数创建它吗?
将您的左值映射到数组中:
const style =
` table:first-of-type thead tr th:first-child{
position: sticky;
position: -webkit-sticky;
background-color:white;
color:crimson;
left: 0px;
z-index: 3;
}
table:first-of-type tbody tr td:first-child{
position: sticky;
position: -webkit-sticky;
background: crimson;
left: 0px;
color:black;
z-index: 1;
}`
+ [30, 138].map((left, idx) =>
`
table:first-of-type thead tr th:nth-child(${idx+2}){
position: sticky;
position: -webkit-sticky;
color: black;
left: 30px;
z-index: 3;
}
table:first-of-type tbody tr td:nth-child(${idx+2}){
position: sticky;
position: -webkit-sticky;
background: black;
left: ${left}px;
z-index: 1;
}
`);
$('pre').text(style);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre></pre>