h5 3d转换实现不了
鼠标经过,虽然翻转了但仍是同一个颜色同一面内容。
代码如下,请前端友友帮忙
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>前后翻转</title>
<style>
body {
perspective: 400px;
}
.box {
transform-style: preserve-3d;
position: relative;
width: 300px;
height: 300px;
margin: 100px auto;
transition: all 1s;
}
.box:hover {
transform: rotateY(180deg);
}
.front,
.back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 50%;
font-size: 30px;
color: #fff;
text-align: center;
line-height: 300px;
}
.front {
background-color: pink;
z-index: 1;
}
.back {
background-color: purple;
transform: rotateY(180deg);
}
</style>
</head>
<body>
<div class="box">
<div class="front">好好学习</div>
<div class="back">天天向上</div>
</div>
</body>
</html>
.front, .back{
backface-visibility: hidden;
}
你的代码里,.front
和 .back
元素都在同一个平面上,所以你看到的始终是.front
元素,因为它的z-index
值更高。
为了使3D转换效果有效,你需要把 .box
元素设为立方体(cube), 在此情况下,你可以通过添加 transform: translateZ(-150px);
到 .box
元素使其成为一个立方体。.front
和 .back
元素分别对应立方体的前面和后面,通过 translateZ(150px)
来放置它们。
所以你可以将代码改写为以下形式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>前后翻转</title>
<style>
body {
perspective: 800px;
}
.box {
position: relative;
width: 300px;
height: 300px;
margin: 100px auto;
transform-style: preserve-3d;
transition: all 1s;
transform: translateZ(-150px);
}
.box:hover {
transform: translateZ(-150px) rotateY(180deg);
}
.front,
.back {
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
font-size: 30px;
color: #fff;
text-align: center;
line-height: 300px;
backface-visibility: hidden;
}
.front {
background-color: pink;
transform: translateZ(150px);
}
.back {
background-color: purple;
transform: rotateY(180deg) translateZ(150px);
}
</style>
</head>
<body>
<div class="box">
<div class="front">好好学习</div>
<div class="back">天天向上</div>
</div>
</body>
</html>
这样,.front
和 .back
元素就会被正确地放置在立方体的前面和后面,实现了你期望的3D翻转效果。另外,backface-visibility: hidden;
确保了元素在旋转时背面不可见。