Ajax动态生成表格如何动态加入样式
时间: 2024-05-11 15:14:53 浏览: 11
您可以使用JavaScript来动态添加CSS样式表,如下所示:
1. 定义一个样式表,在其中添加所需的样式:
```css
<style>
.table {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
font-size: 14px;
}
.table th, .table td {
text-align: left;
padding: 8px;
border: 1px solid #ddd;
}
.table th {
background-color: #f2f2f2;
color: #444;
}
</style>
```
2. 使用 JavaScript 创建一个新的 style 元素并将样式表添加到其中:
```js
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.table { border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 14px; } .table th, .table td { text-align: left; padding: 8px; border: 1px solid #ddd; } .table th { background-color: #f2f2f2; color: #444; }';
document.getElementsByTagName('head')[0].appendChild(style);
```
3. 将样式应用到表格中:
```js
var table = document.createElement('table');
table.className = 'table';
// 添加表格头部和内容...
document.body.appendChild(table);
```
这样,您的表格就拥有了指定的样式!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)