[英]how can I use a JS function to change an element style in the page
I need 2 simple JavaScript functions that read and change the color of a div on click. 我需要2个简单的JavaScript函数,这些函数可以在单击时读取并更改div的颜色。 I don't want to use frames, jQuery any other means but simple html, css, JS.
我不想使用框架,jQuery,而是使用简单的html,css,JS。 The code that I have wrote and doesnot work is as follows:
我已编写但无法正常工作的代码如下:
Randomize colours 随机颜色
<script>
var colorArray = {yellow, red, blue, purple};
function readColor () {
color = document.getElementById("color");
}
function changeColor (color) {
var randomColor = colorArray[Math.floor(Math.random() * colorArray.length)];
document.getElementById('color').style.backgroundColor = randomColor;
var colors = document.getElementById('color');
colors.style.backgroundColor = color;
}
</script>
<style type = "text/CSS">
<!--
#color {
background-color: yellow;
}
-->
</style>
<div id="color" style="border-color: #eee; border-style: solid; width: 300px; height: 300px; margin-right: auto; margin-left: auto; margin-top: 200px; padding: 50px; background-color: yellow;" onChange = "readColor ();">
Aici are loc lupta
</div>
<div style="text-align: center; margin-top: 20px;">
<input type="button" name="Change color" value="Change Color" onClick = "changeColor ()">
</div>
I believe just changing 我相信只是改变
var colorArray = {yellow, red, blue, purple};
to 至
var colorArray = ['yellow', 'red', 'blue', 'purple'];
should do it.. 应该做..
Demo at http://jsfiddle.net/pYc4P/ 演示在http://jsfiddle.net/pYc4P/
I think the problem is that you are not passing in color on the onclick 我认为问题是您没有在onclick上传递颜色
Should it not read: 它不应该显示为:
<input type="button"
name="Change color"
value="Change Color"
onClick = "changeColor (color)">
You create colorArray
as an object, but you are using it as an array. 您将
colorArray
创建为对象,但是将其用作数组。
Try declaring it as an array instead: 尝试将其声明为数组:
var colorArray = new Array("yellow", "red", "blue", "purple");
Or: 要么:
var colorArray = ["yellow", "red", "blue", "purple"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.