【问题标题】:Why is my animated div moving diagonally?为什么我的动画 div 沿对角线移动?
【发布时间】:2019-10-22 11:00:39
【问题描述】:

我正在尝试通过向一侧打开一副窗帘来为我的网页设置动画。我使用 CSS 并通过将 div 的位置移出屏幕来实现此结果。但是,当我编写一个按钮以将动画状态从暂停切换到运行时,div 会沿对角线移出屏幕并在此过程中淡出。为什么?

#curtainLeft{
position: absolute;
z-index: 3;
top:0;
left: -1000px;
height:100%;
animation-name:left;
animation-duration: 1.5s;
animation-play-state: paused;

}
@keyframes left {
from {left: 0px;}
to {left: -1000px;}
}

#curtainRight{
position:absolute;
z-index: 3;
top:0;
right:-1000px;
animation-name:right;
animation-duration: 1.5s;
animation-play-state: paused;

}
@keyframes right {
from {right: 0px;}
to {right: -1000px;}
}

.runAnimation{
animation-play-state: running;
}


<button id="directionsButton" onclick="myFunction()">Begin</button>
</div>
<div id="curtainLeft">
    <img src="./assets/images/curtainLeft.png">
</div>
<div id="curtainRight">
    <img src="./assets/images/curtainRight.png">
</div>



function myFunction(){

$("#curtainRight").toggle("runAnimation");
$("#curtainLeft").toggle("runAnimation")
$("#directionsButton").remove();
audio.play();
}

【问题讨论】:

    标签: jquery css animation


    【解决方案1】:

    首先,我认为这是一个错误,但后来我注意到,runAnimation 类从未分配给 div,然后我看到动画本身完全由 js 处理。答案很简单。你误用了.toggle() - 它隐藏/显示元素的功能,.toggleClass() 是你想要的。

    您还需要为animation-play-state: running 添加!important,因为它是类的样式,而animation-play-state: paused; 是具有更高优先级的id 的样式。或者你可以像#curtainLeft.runAnimation {...} 这样写它,然后它会有更高的优先级,你就不需要!important。显然,将窗帘包裹到一个共同的父级中是个好主意,该父级将具有overflow: hidden; 和可能有pointer-events: none;。我只是在 sn-p 中使用了body

    $('#directionsButton').click(() => {
      $("#curtainRight").toggleClass("runAnimation");
      $("#curtainLeft").toggleClass("runAnimation")
      $("#directionsButton").remove();
    });
    body {overflow: hidden;}
    
    #curtainLeft,
    #curtainRight {
      height: 100%;
      width: 50%;
      position: absolute;
      z-index: 3;
      top: 0;
      animation-duration: 1.5s;
      animation-play-state: paused;
    }
    
    #curtainLeft {
      left: -1000px;
      background: firebrick;
      animation-name: left;
    }
    
    #curtainRight {
      right: -1000px;
      background: rebeccapurple;
      animation-name: right;
    }
    
    #directionsButton {
      position: absolute;
      left: 10px;
      right: 10px;
      z-index: 10000;
    }
    
    .runAnimation {
      animation-play-state: running !important;
    }
    
    @keyframes left {
      from {left: 0;}
      to {left: -1000px;}
    }
    
    @keyframes right {
      from {right: 0;}
      to {right: -1000px;}
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="directionsButton">Begin</button>
    <div id="curtainLeft"></div>
    <div id="curtainRight"></div>

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 2015-10-30
      • 2023-03-22
      • 2013-08-09
      • 1970-01-01
      • 2014-09-19
      相关资源
      最近更新 更多