繁体   English   中英

使用JavaScript在div上进行动态颜色更改

[英]Dynamic colour changes on divs using javascript

我需要帮助。 我无法使用javascript动态更改下面代码中列出的三个div的颜色。 我已经在下面粘贴了完整的代码...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style>
.box{
width:100px;
height:100px;
}
</style>
</head>

<body>
<div class="box">
quote 1
</div>
<div class="box">
quote 2
</div>
<div class="box">
quote 3
</div>

<script type="text/javascript">
var bgcolorlist=new Array( "#ff33cc", "#cc33ff")

$(".box").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]);
</script>

</body>
</html>

您正在$(".box").css()上使用jQuery,但尚未链接库! 在当前脚本之前添加以下内容:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

或者,根本不使用jQuery:

var boxes = document.querySelectorAll('.box');
for(var i=0; i<boxes.length; i++) {
    boxes[i].style.backgroundColor = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM