在我的代码中,我有一个图像,每次我用鼠标单击它时,它都会交换到另一个图像。我在向第二个(交换的)图像中添加随机文本时遇到了困难。当我看到第一张图片时,文本不应该出现。这是我的代码。当我尝试为随机文本编写代码时,java脚本中有一些错误。请帮我改正。
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1></h1>
<div id="cookie" class='whole'></div>
</div>
<p id="demo"></p>
<script src="js/cookies.js"></script>
</body>
</html>js代码:
var lock = document.getElementById('cookie');
var state = 'orange';
function swapImage(){
if (state === 'orange'){
lock.className = 'cracked';
state = 'blue';
}else{
lock.className = 'whole';
state = 'orange';
}
}
lock.addEventListener('click', swapImage, false);
var r_text = new Array ();
r_text[0] = "All the leaves are brown";
r_text[1] = "And the sky is grey";
r_text[3] = "On a winter's day";
r_text[4] = "I'd be safe and warm";
r_text[6] = "California dreaming, On such a winter's day";
var i = Math.floor(7*Math.random())
function fortune() {
document.write(r_text[i]);
}
var elText = document.getElementById('cookies');
elText.addEventListener('click', fortune, false); css:
#cookie{
width: 360px;
height: 216px;
margin: 100px auto;
margin-top: 10px;
}
.whole {
background: url("../images/whole.png");
}
.cracked {
background: url("../images/cracked.png");
}发布于 2015-03-23 08:28:47
您必须在fortune函数中运行var i = Math.floor(7*Math.random()),否则i将与以前一样。
https://stackoverflow.com/questions/29201480
复制相似问题