Как я могу оживить текст из одного div в другой? - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть два div, которые действуют как две строки для отображения подписей. новый заголовок отображается в строке 2, заголовок строки 2 переходит к строке 1, заголовок строки 1 перестает отображаться. (строка 2 находится ниже строки 1),

Я хочу анимировать текст, чтобы при добавлении строки 2 с новым заголовком, а строка 1 получала заголовок строки 2, заголовок перемещался из строки 2 в строку 1 вместо того, чтобы сразу помещаться в строку 1.

КОД: (игнорировать js код до тех пор, пока комментарий не «начнется здесь», это просто манипулирование данными заголовка.)

https://jsfiddle.net/wzs8oruh/2/

если вы запустите это, вы поймете, что я пытаюсь сказать. Я хочу, чтобы 2-я строка анимировала его содержимое в первую строку, а затем обновила его. вместо того, что происходит сейчас, мгновенно.

(subCaptions - это массив с объектами титров в форме {"start": 1585180670495, "end": 1585180678735, "transcript": "captionText"} )

JS часть, которая обновляет текст в двух делениях:

let line1 = document.getElementById("caption-text-1");
let line2 = document.getElementById("caption-text-2");

//randomly set asper the first caption data start time.. increases by one second every second
let playerTime = 1585180668495;

let displayArray = [];

function updateCaptionsText() {

    if (!isNaN(playerTime) && playerTime > 0) {

        //if caption exists to show
        if(subCaptions[0]){

            if( playerTime >= subCaptions[0].start ){

                //display array can have at max two caption data to show in two lines. first object in line1, second in line2. if 2 already exist, remove first and append to it new caption.
                if( displayArray.length >= 2 ){
                    displayArray.shift();
                    displayArray.push(subCaptions.shift());
                }else{
                    displayArray.push(subCaptions.shift());
                }
            }   
        }

        //update divs with displayArray's contents
        switch(displayArray.length){
            case 0:
                line1.textContent = "";
                line2.textContent = "";
                break;
            case 1:
                line1.textContent = "";
                line2.textContent = displayArray[0].transcript;
                break;
            case 2:
                line1.textContent = displayArray[0].transcript;
                line2.textContent = displayArray[1].transcript;
                break;
            default:
                break;
        }

    }  

  }

  setInterval(() => {
    playerTime += 1000;
    updateCaptionsText();
  }, 1000); 

1 Ответ

1 голос
/ 09 апреля 2020

изменено JS: (с учетом указанных подзаголовков)

function getNewcaptionDiv(captionText){
    var iDiv = document.createElement('div');
    iDiv.className = "capText";
    iDiv.innerText = captionText;
    iDiv.style.height="35px";
    if(captionText === ""){
        iDiv.style.padding=0;
    }
    return iDiv
}
function display(iDiv){
    if(captionsParentDiv.childNodes.length==2){
        captionsParentDiv.removeChild(captionsParentDiv.childNodes[0]);
    }
    captionsParentDiv.appendChild(iDiv);
}
function updateCaptionsText() {
    if (!isNaN(playerTime) && playerTime > 0) {
        if(subCaptions[0]){
            if( playerTime >= subCaptions[0].start ){            
                display(getNewcaptionDiv((subCaptions.shift()).transcript));
            }   
        } 
    }
}
function initCaptionsDiv(){
    captionsParentDiv = document.getElementById("caption-texts");
    captionsParentDiv.appendChild(getNewcaptionDiv(""));
    setInterval(() => {
        playerTime += 1000;
        updateCaptionsText();
        }, 1000);
}
initCaptionsDiv();

изменено HTML:

<!doctype html>

<html lang="en">
<head>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta charset="utf-8">
  <title>Captions update algo</title>
</head>
<body>
  <div id="caption">
    <div id="captionBottom">
      <div id="caption-texts" class="captionText"></div>
    </div>
  </div>
  <script src="captionsUpdate3.js"></script>
</body>
</html>

изменено css:

#caption{
    margin-left: auto;;
    margin-right: auto;
    margin-top: auto;
    margin-bottom: 10%;
    height: 74px;
    width: 80%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}
#captionTop{
    height: 60px;
}
#captionBottom{
    height: 74px;
}
.captionText{

    font-size: 1.4vw;

    color: white;
    font-weight: 900;
    line-height: 35px;
    margin: 2px;
    position: relative;
}
body{
    background:linear-gradient(180deg, #074595 0%, #6589A4 100%);
    background-repeat: no-repeat;
    height: 100vh;
}
.capText{
    width: max-content;
    height: 35px;
    padding-left: 10px;
    padding-right: 10px;
    margin: 2px;
    text-align: center;
    background-color: black;
    margin-left: auto;
    margin-right: auto;
}

.capText:first-child {
    -webkit-animation: move 0.4s ease-out;
    animation: move 0.4s ease-out;
}

@-webkit-keyframes move {
    0% {margin-top: 35px;}
   100% {margin-top: 2px;}
}

@keyframes move {
    0% {margin-top: 42px;}
   100% {margin-top: 2px;}
}

Должен получить то, что вы хотите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...