簡體   English   中英

如果滿足PHP條件,如何運行CSS關鍵幀?

[英]How to run CSS keyframes if PHP condition is met?

我有一個開場動畫,只有在用戶第一次訪問該網站時,我才想運行它。 我不希望用戶每次重新加載頁面時都看到動畫,所以我希望動畫僅在未為用戶設置Cookie的情況下才能運行。

偽代碼示例:

if (cookie(userAlreadyVisited) is set {
doAnimation
}
else
{
doNotAnimate
}

動畫將是這樣的:

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Div animation</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<div id="main"><h1 id="headline-fade">Welcome!</div>
</body>
</html>

CSS:

body {
    background-color: black;
    display: flex;
    justify-content: space-around;
}

#main {
    animation-name: example;
    animation-duration: 1.5s;
    position: relative;
    top: 50px;
    width: 750px;
    height: 500px;
    background-color: white;
    border-radius: 2px;
    display: flex;
    justify-content: space-around;
}

#headline-fade {
    animation-name: fontFade;
    animation-duration: 3s;
    margin: auto;
    font-family: Roboto;
}

@keyframes example {
    0% {
        background-color: white;
        width: 2px;
        height: 2px;
    }
    50% {
        background-color: white;
        width: 2px;
        height: 500px;}
    100% {
        background-color: white;
        width: 750px;
        height: 500px;
    }
}

@keyframes fontFade {
    0% {
        opacity: 0;
        margin: auto;
    }
    50% {
        opacity: 0;
        margin: auto;
    }
    100% {
        opacity: 1;
        margin: auto;
    }
}

總而言之,我只希望關鍵幀在用戶第一次訪問或cookie已過期時運行。 我已經嘗試過jQuery.Keyframes,但無法正常工作。

僅當animation在CSS中具有特定的類時才設置animation ,而在PHP(或javascript)中,如果用戶已經訪問過該animation則僅給該元素該類。

讓PHP確定cookie是否存在,並在條件語句中使用該cookie將可能沒有動畫的類添加到元素中。

然后,您可以使用該類擴展CSS,並將動畫樣式僅應用於具有此類的元素。

舉個例子:

在您的CSS中:

#main {
    position: relative;
    top: 50px;
    width: 750px;
    height: 500px;
    background-color: white;
    border-radius: 2px;
    display: flex;
    justify-content: space-around;
}
#main.animated {
    animation-name: example;
    animation-duration: 1.5s;
}

@keyframes example {
    0% {
        background-color: white;
        width: 2px;
        height: 2px;
    }
    50% {
        background-color: white;
        width: 2px;
        height: 500px;}
    100% {
        background-color: white;
        width: 750px;
        height: 500px;
    }
}

在您的HTML中:

<div id="main" <?php if (!isset($_COOKIE['userAlreadyVisited'])) { echo class='animated' }; ?>>
<h1 id="headline-fade">Welcome!</h1>

PS:您的原始代碼示例中缺少</h1>標記。

只要保持一切相同,期望像這樣將php代碼與html集成,我想這會完美地工作。

    <?php if (!isset($_COOKIE['userAlreadyVisited'])) { 
?>
<div id="main"><h1 id="headline-fade">Welcome!</div>
<?php
} ?>

在這里isset將檢查cookie是否已存儲,然后只是一個簡單的if條件,如果它為true,它將執行該語句(在您的情況下為welcome消息),如果不是true,它將跳過Welcome消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM