怎样让Javascript的值传到css里面去?

xiaxin 2004-07-16 02:27:30
下面is的值是1-7的随机数。

<script>
id = Math.round(Math.random()*2)+1;
ic = Math.round(Math.random()*2)+1;
is=id+ic;
if ((id == 2)&&(ic == 2))
{
is=1;
}
if ((id == 3)&&(ic == 2))
{
is=7;
}
document.write("这是" + is + "数");
</script>

我想将is的1-7分别代表7种颜色,传到下面的CSS里。有什么方法吗?
传到 background:#d90005;去。好让我的网页某个表格颜色刷新一次变一次。

<style type="text/css">
.class2
{
background:#d90005;
}
</style>
...全文
301 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
GageCSDN 2004-07-16
  • 打赏
  • 举报
回复
楼上的这些办法好像都可以,但是要修改样式表,就要:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>change color</title>
<script language="javaScript">
id = Math.round(Math.random()*2)+1;
ic = Math.round(Math.random()*2)+1;
is=id+ic;
if ((id == 2)&&(ic == 2))
{
is=1;
}
if ((id == 3)&&(ic == 2))
{
is=7;
}

//建立一个待选颜色数组
var arrColor = new Array("blue","red","green","#336699","#3399cc","#006699","yellow");
//页面加载后设置颜色
function window.onload()
{
var obj = document.styleSheets[0].rules[0]; //取得第一个<style>里的第一个样式
obj.style.backgroundColor = arrColor[is]; //设置它的颜色
}
</script>
<!--这个style一定要放在其它的style标签前面,而且要修改的.class2也要放到这个标签里的第一个位置-->
<style type="text/css">
.class2
{
background-color:#d90005;
}
</style>
</head>
<body>
<table width="50" height="30" class="class2">
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
starwu 2004-07-16
  • 打赏
  • 举报
回复
this.style.cssText = "background-color: #" + s
starwu 2004-07-16
  • 打赏
  • 举报
回复
可以用:
this.style.cssText.background = "#" + s
LxcJie 2004-07-16
  • 打赏
  • 举报
回复
不能传到css里面

但是可以使用js控制样式

一般的格式为:

obj.style.css样式 = 。。。

<table id=table1>

</table>

document.all.table1.style.backgroundColor = "#FFFFFF";
document.all.table1.style.backgroundColor = "#000000";
...

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧