如何在 JavaScript 中进行堆叠 Div 的转换

how to make transition of stacked Divs. in JavaScript

本文关键字:Div 转换 JavaScript      更新时间:2023-09-26

我正在尝试使用html5,CSS3和JS制作"内存游戏"。我已经完成了这个游戏的视图和模型部分,现在正在尝试制作控制器。我想要的是调用一个函数,即在 JS 中翻转并希望该函数执行转换而不是使用 CSS3 的悬停效果。基本上我正在尝试遵循这种方法。 我检查了使用悬停在 css3 中翻转,如下面的 sass 代码所示,但对于游戏,用户决定点击位置。为简单起见,我简洁了 html5 中的代码,因为它对所有其他div 重复。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>I Don't Know</title>
    <link rel="stylesheet" href="trapStyle.css">
</head>
<body>
   <div  class = "container" >
    <div class="sub1" >
    <div class="front" id="card1"  onclick="flip(card1)">card1</div>
    <div class="back" id="card1_1">what the hell?</div>
    </div>   <--sub1 Ends-->
    <div class="sub1">
    <div class="front" id="card2" onclick="flip(this)">card2</div>
    <div class="back" id="card2_2">what the hell?
    </div>   <--sub1 Ends-->
    </div>  <-- container Ends -->

    <script src ="script.js"></script>
</body>
</html>

和 CSS 的 SASS 代码

.container {
    position: absolute;
    left: 115px;
    width: 1150px;
    height: 700px;
    background-color: silver;
/* SUB-CONTAINER to stack two cards */
    .sub1 {
        width: 200px;  height: 200px;
        float:left; margin: 5px;
        .front {
            position:absolute;  width: 200px;  height: 200px;
            background-color: #498010;
            transform: perspective( 600px) rotateY(0deg);
            backface-visibility: hidden;
            transition: transform 0.5s linear 0s;
        }
        .back {
            position: absolute;  width: 200px;  height: 200px;
            float:left;   background-color: #689;
            transform: perspective( 600px) rotateY(180deg);
            backface-visibility: hidden;
            transition: transform 0.5s linear 0s;
        } 

    }
    .sub1:hover > .front {
/*    transform: perspective(600px) rotateY(-180deg); */
}
       .sub1:hover > .back {
    /* transform: perspective(600px) rotateY(0deg); */
}
}

和 JavaScript

function flip(front) {
    document.getElementById("front").style.transition = opacity 0.5s linear 0s;
    document.getElementById("front").style.opacity = 0;
}

注意:上面的链接试图将 id 传递给发生转换的 JS 函数。这里正在做同样的事情,只是为了从用户那里获取输入,而不仅仅是悬停,但什么也没发生!我在编辑器中复制/粘贴链接代码并执行平滑过渡,但是当涉及到我的代码时,什么都没有!你能告诉我我的缺点在哪里吗?

将 CSS 从悬停状态更改为类,对于 iunstance,请将 .sub1:hover 更改为 .hovered:

 .container .hovered > .front {
    transform: perspective(600px) rotateY(-180deg); }
  .container .hovered > .back {
    transform: perspective(600px) rotateY(0deg); }

现在,在单击时,将此类添加到单击的元素中:

$(".sub1").click(function() {
   $(this).addClass ('hovered');   
})

小提琴

JavaScript中的这个函数将是

function change(element) {
    element.className = element.className + " hovered";
}

前提是您在函数调用中发送元素

onclick="change(this)"

小提琴 - 仅在第一个div 中设置的功能