Javascript / Html / Css随机背景图像&来自两个javascript数组的单词

时间:2016-07-29 09:08:12

标签: javascript html css

欢迎来到论坛! 今天我想用Javascript / html / css / php语言编写一些代码,但我遇到了问题。 (我到处都搜索过这个问题,但没有结果。)

我的问题是=>我的js文件中有两个数组。第一个存储目录中的图片,第二个存储我想要通过Math()编号#indexes随机选择的单词 您可以阅读我的代码中的所有内容。我评论过他们。

window.onload = chooseGame;

var cGamePic = new Array("football.jpg","baseball.jpg");
var cGameName = new Array("football","baseball");
function chooseGame;
	var rnd_num = Math.floor(Math.random() * cGamePic.length);
	document.getElementById("comp1Game").src = cGamePic(rnd_num);
    document.getElementById("??").?? = cGameName(rnd_num);
<!DOCTYPE html>
<html>
	<head>
		<title>Random pics</title>
		<script src="rnd.js"></script>
		<link rel="stylesheet" type="text/css" href="style.css">
	</head>
	<body>
		<div id="container1">
			<h1>Some text 1</h1>
			<!--The next line will be displayed,but not randomly.
			And I want it to the left-side of screen,as background image.
			Like: the text "Some text 1" will be displayed in the random selected image.
			(The some text 1 is selected randomly too,as "football")
			-->
				<img src="res/images/football.jpg" id="comp1Game" alt="Compare1">
		</div>
	
		<div id="container2">
			<h1>Some text 2</h1>
			<!-- The future container to see the 2nd selected image & word in it (right side of screen)
			Like,if js select number 6,the word and image will be "baseball" and "baseball.jpg"
			Shortly,I want to do it.
			-->
		</div>
	</body>
</html>

2 个答案:

答案 0 :(得分:0)

使用jQuery更容易:

<!DOCTYPE html>
<html>
    <head>
        <title>Random pics</title>
        <script src="rnd.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script> 
    var cGamePic = new Array("football.jpg","baseball.jpg");

    $( document ).ready(function() {
        chooseGame();
    });

    function chooseGame(){
        var pic = cGamePic[Math.floor(Math.random()*cGamePic.length)];
        var name = pic.replace(/^.*[\\\/]/, '');

        $("#comp1Game").attr("src",pic);
        $("#container1 h1").html(name);
    }
</script> 

    </head>
    <body>
        <div id="container1">
            <h1>Some text 1</h1>
            <img src="res/images/football.jpg" id="comp1Game" alt="Compare1">
        </div>
    </body>
</html>

答案 1 :(得分:0)

让它变得简单

如果数组[GameName]和[GamePicture]值在同一索引中,则只需按照以下代码段进行操作

var cGamePic = new Array("football.jpg","baseball.jpg");
var cGameName = new Array("football","baseball");
var randomItem = Math.floor(Math.random() * cGamePic.length);
var comp1GameTitle = document.querySelector("#container1 h1");//Heading from main container
var comp1GameImage = document.querySelector("#container1 img");//Image from main container
comp1GameTitle.innerHTML = cGameName[randomItem]; //Random Title
comp1GameImage.src=cGamePic[randomItem]; //Random image 

Demo