我有一个数字游戏,其中有一个4x4板。对于第1行,每个块的名称是board11,board12,board13,board14。这是怎么回事。 然后在每个块上都是来自css的png图像。 这是CSS代码的片段:
Student[] students = JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass)).ToArray();
每个区块的图像都可以改变。随机化将在javascript中完成。 我想要做的是将背景图像从css获取到javascript,为它分配一个值(1.png是1,2.png是2等),这样每次我点击块/图像,它会显示在我的记分牌上(值+ 5)。所以点击7.png将得到12分。
我的主要问题是,我不确定如何从css获取图像并分配值。 这是我到目前为止(javascript):
div#gamearea4x4 div.row1#board11{
background-image: url(../graphics/9.png); //images are from 1.png to 9.png
width: 50px;
height: 50px;
单击图像/块时:
function StartGame() {
///// this function gets the board id(loop) and assigns a random img to it
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
var id = 'board' + (i + 1) + (j + 1); //loop for the board id
var w = val[Math.floor(Math.random()*img.num.length)]; //getting a random value
var obj = document.getElementById(id);
var uu = 'url(graphics/' + w + '.png)'; //random image generated from random value
document.getElementById(id).style.backgroundImage = uu; //setting it as the id's image
}
}
这是HTML的片段:
function ImageOnClick(target) {
///// this function will calculate the score
var vvv = document.getElementById(target).style.backgroundImage; //gets targeted id
document.getElementById(target).style.display='none'; //img disappears when clicked
score = score + 5; // incomplete equation. var score defined on top.
document.getElementById('scoreval').innerHTML= score ;
}
非常感谢任何帮助!谢谢!
答案 0 :(得分:0)
使用属性
function StartGame() {
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
var id = 'board' + (i + 1) + (j + 1); //loop for the board id
var w = val[Math.floor(Math.random()*img.num.length)]; //getting a random value
var obj = document.getElementById(id);
var uu = 'url(graphics/' + w + '.png)'; //random image generated from random value
document.getElementById(id).style.backgroundImage = uu; //setting it as the id's image
document.getElementById(id).setAttribute("data-position", w);//set the attribute
}
}
}
function ImageOnClick(target) {
///// this function will calculate the score
var vvv = document.getElementById(target).getAttribute("data-position") //gets targeted id
document.getElementById(target).style.display='none'; //img disappears when clicked
score = score + 5; // incomplete equation. var score defined on top.
document.getElementById('scoreval').innerHTML= score ;
}
答案 1 :(得分:0)
我的主要问题是,我不确定如何从css获取图像并分配值。
如果正确解释问题,您可以使用background-image
,css
并window.getComputedStyle()
String.prototype.replace()
RegExp
检索/^url(?=\()|\(|\)|"/
属性
window.onload = function() {
var elem = document.getElementById("board11");
var url = window.getComputedStyle(elem).getPropertyValue("background-image");
console.log(url.replace(/^url(?=\()|\(|\)|"/g, ""));
}
&#13;
div#gamearea4x4 div.row1#board11 {
background-image: url(http://lorempixel.com/1/1); //images are from 1.png to 9.png
width: 50px;
height: 50px;
}
&#13;
<div id="gamearea4x4">
<div class="row1" id="board11"></div>
</div>
&#13;