使用background-position 是一种众所周知的将图像分割成小块的方法。通过该技术,您可以逐步解决您的问题。我已经尝试过这段代码来演示技术并解决您的问题。
HTML:
<div class='canvas'></div>
CSS:
.canvas {
background:url('http://placekitten.com/500/300');
width:500px;
height:300px;
}
.cell {
float:left;
position:relative;
cursor:pointer;
}
.cell > .front {
-webkit-backface-visibility: hidden;
backface-visibility:hidden;
-webkit-transform-style:preserve-3d;
transition:all 1s;
}
.cell:not(.flipped) > .back {
-webkit-transform:rotateY(180deg);
}
.cell.flipped > .front {
-webkit-transform:rotateY(180deg);
}
.back {
background:pink;
}
.cell > .back {
position:absolute;
text-align:center;
font-size:30px;
color:red;
left:0;
top:0;
transition:all 1s;
}
.cell > .back:before {
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
}
.cell > * {
border: 1px solid orange;
box-sizing:border-box;
width:100%;
height:100%;
}
JS:
//get the canvas
var canvas = $('div.canvas');
var backgroundImage = canvas.css('background-image');
//remove the background from canvas
canvas.css('background-image','none');
//number of columns and rows
var col = 8;
var row = 4;
var colWidth = canvas.width() / col;
var rowHeight = canvas.height() / row;
//loop through the cells
for(var i = 0; i < row; i++){
for(var j = 0; j < col; j++){
//append new cell to canvas
var cell = $("<div class='cell flipped'><div class='back'>?</div><div class='front'></div></div>")
.width(colWidth).height(rowHeight).appendTo(canvas);
//set the background for the cell
//note that calculate the em unit for more flexible
//font-size
cell.find('.front')
.css('background',backgroundImage)
.css('background-position', -(j * colWidth) + 'px ' + -(i * rowHeight) + 'px');
//register click handler for the cell
cell.click(function(){$(this).toggleClass('flipped')});
}
}
注意:请在基于 webkit 的浏览器中测试演示,我刚刚为基于 webkit 的浏览器添加了前缀(对于backface-visibility、transform,...)。另请注意,此代码并不完整,它只是帮助您开始满足您的实际需求。
关于 CSS 的一点解释,实际上你需要在一个单元格上有 2 个面,.front 和 .back 面,.front 用于渲染图像,.back 用于渲染文本(在单元格之后翻转)。在翻转状态下,.front 应围绕Y 轴(垂直轴)旋转180deg,但其backface-visibility 应设置为hidden。相反,.back 应该在正常状态下围绕 Y 轴旋转180deg。
更新:有些浏览器不支持backface-visibility 功能(例如Maxthon),所以你有另一个漂亮的解决方法是使用@ 987654341@ 代替。在翻转状态下,.back 应该有更高的z-index(例如1)来覆盖.front,而在正常状态下,它应该有一个零z-index,以便它隐藏在.front 后面.这是Updated Demo在不支持backface-visibility的浏览器上工作)