css部分
.card2d {
position: absolute;
}
.card {
100%;
height: 100%;
cursor: pointer;
}
.card-a {
background-color: red;
color: white;
text-align: center;
font-size: 30pt;
}
.card-b {
background-color: blue;
}
html部分
<div id="game-div">
</div>
js部分
window.ucai = window.ucai || {};
(function () {
function Card(number) {
this._width = 48;
this._height = 48;
this._number = number;
this._htmlNode = document.createElement("div");
this._htmlNode.className = "card2d";
this._cardA = document.createElement("div");
this._cardA.className = "card card-a";
this._cardA.innerHTML = "" + this._number;
this._htmlNode.appendChild(this._cardA);
this._cardB = document.createElement("div");
this._cardB.className = "card card-b";
this._htmlNode.appendChild(this._cardB);
this._htmlNode.style.width = this._width + "px";
this._htmlNode.style.height = this._height + "px";
this.showA();
var self = this;
this._htmlNode.addEventListener("click", function (e) {
if (self.onclick) {
self.onclick(self);
}
});
}
var p = Card.prototype;
p.getWidth = function () {
return this._width;
};
p.getHeight = function () {
return this._height;
};
p.showA = function () {
this._cardA.style.display = "block";
this._cardB.style.display = "none";
this._aVisble = true;
};
p.showB = function () {
this._cardA.style.display = "none";
this._cardB.style.display = "block";
this._aVisble = false;
};
p.isAVisible = function () {
return this._aVisble;
};
p.getHtmlNode = function () {
return this._htmlNode;
};
p.getNumber = function () {
return this._number;
};
/**
* 设置位置
* @param {number|Object} xOrPosition
* @param {number} y
*/
p.setPosition = function (xOrPosition, y) {
switch (arguments.length) {
case 1:
this._htmlNode.style.left = xOrPosition.x + "px";
this._htmlNode.style.top = xOrPosition.y + "px";
break;
case 2:
this._htmlNode.style.left = xOrPosition + "px";
this._htmlNode.style.top = y + "px";
break;
}
};
ucai.Card = Card;
})();
(function () {
var gameDiv = document.querySelector("#game-div");
var allPoints = [];
var currentNumber = 1;
var cards = [];
function createPoints() {
allPoints.length = 0;
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
allPoints.push({x: 50 * i, y: 50 * j});
}
}
}
function cClickedHandler(card) {
if (currentNumber == card.getNumber()) {
gameDiv.removeChild(card.getHtmlNode());
var index = cards.indexOf(card);
if (index != -1) {
cards.splice(index, 1);
if (currentNumber == 1) {
for (var i = 0; i < cards.length; i++) {
cards[i].showB();
}
}
if (cards.length <= 0) {
alert("成功了");
}
}
currentNumber++;
} else {
alert("点错了");
}
}
function addCards() {
cards.length = 0;
for (var i = 1; i <= 6; i++) {
var c = new ucai.Card(i);
gameDiv.appendChild(c.getHtmlNode());
cards.push(c);
var index = Math.floor(Math.random() * allPoints.length);
c.setPosition(allPoints[index]);
allPoints.splice(index, 1);
c.onclick = cClickedHandler;
}
}
function init() {
currentNumber = 1;
createPoints();
addCards();
}
init();
})();