SVG меняют размер, но не ожидают перехода на прокрутку

У меня есть нижний колонтитул/ряд SVG, которые я сделал, но они не могут анимироваться во время перехода между 1-м и 2-м разделами. Код не прост для отладки, потому что ему нужно анимировать, если js управляет размером нескольких элементов. Ряд смелых пользователей придумали решения, которые работают в Chrome и Firefox, но чтобы получить кредит, решение должно работать и в Safari.

Я проверил, что классы, которые я добавляю при переходе (.fixed), действительно применяются, потому что они используют изменения размера SVG. Поэтому, в то время как SVG меняют размеры, по какой-то причине я все еще не могу получить переходы CSS для анимации. Вы можете просмотреть этот отказ для анимации в GIF ниже.

Нижний колонтитул не анимируется:

css Переход не работает/анимировать

Элементы, которые, я считаю, нуждаются в коде перехода, - это сами SVG, которые относятся к классу areaSVG, потому что это те, кто меняется от max-height: 18vh до max-height: 9vh.. Однако, когда я добавляю некоторый код анимации в .areaSVG, это не сработало, поэтому, возможно, я ошибаюсь. Вот код перехода, который я попробовал добавить к исходным настройкам SVG (.areaSVG):

  -webkit-transition: max-height 1s;
  -moz-transition: max-height 1s;
   transition: max-height 1s;

Несколько месяцев назад, с помощью другого, более опытного кодера, я добавил функцию javscript, которая в какой-то момент анимировала SVG. Мы использовали JS для вызова window.requestAnimationFrame(startAnimation), но он больше не работает. Я прокомментировал детали, связанные с этим, но если вы можете подумать, что JS понадобится для анимации, не стесняйтесь разворачивать ручку кода и играть с ней. Подходящий ответ должен заставить анимацию работать в Safari, Chrome и Firefox.

Codepens

  • Это самая легкая, сведенная к минимуму версия, с которой вы должны устранять неполадки, поскольку она не имеет медиа-запросов (по запросу @Eric N: http://codepen.io/ihatecoding/pen/LREOPW

  • Это полный код, с медиа-запросами: http://codepen.io/ihatecoding/pen/ALjKKz

Селекторы

Селекторы в первом разделе (вверху страницы):

  • Весь нижний колонтитул: #indexFooter
  • Родители SVG: .ey-col-svg
  • Сам SVG: .areaSVG

Селекторы во второй секции (после прокрутки на 100 пикселей вниз):

  • Весь фиксированный нижний колонтитул: #indexFooter.fixed
  • Фиксированные родители SVG: .ey-col-svg.fixed
  • Фиксированный сам SVG: .areaSVG.fixed

Примечание. Когда страница сначала загружает родителя SVG (.ey-col-svg), а сам SVG (.areaSVG) невидим и имеет параметр display:none, чтобы избежать странного опыта для пользователя.

Вот информация о важных элементах в каждом разделе:

Большой нижний колонтитул (в первом разделе)

Введенный CSS (первый раздел)

  /* The whole footer container */
  #indexFooter {

   text-align: center;
    box-sizing: border-box;
    position: fixed;
    vertical-align: middle;
    bottom: 0;
    left: 0;
    z-index: 5000;
    max-height: 33.33vh;
    width: 100%;
}


/* The SVG container*/
.ey-col-svg {
   display: none;
   height: auto;
    text-align: center;
    box-sizing: border-box;
    padding: 0;

}

/* The SVG */    
.areaSVG {
   display: none;
   max-height: 18vh;  
   box-sizing: content-box;
   margin: 0;

}

Далее, JS запускается, а затем отображает элементы (все еще в первом разделе):

/* The SVG container*/
.ey-col-svg {
   display: block;    
}


/* The SVG*/
.areaSVG {
   display: inline-block;    
}

Малый нижний колонтитул (пока ниже первой секции)

После выхода из первой секции (когда нижний колонтитул должен быть меньше и фиксирован)

/* The SVG when low on page*/
.areaSVG.fixed {
    max-height: 9vh;
}

Javascript/JQuery

Вот Javascript, если вы хотите его увидеть

 $(document).ready(function() {


    var sectionIndex = 1;
    var animationName = 'indexAnimateLand';


    startAnimation();   //includes resizing background image and resizing svgs
    toggleIntroClass();  //adds css depending on section of page



    // if the user resizes the window, run the animation again, 
    // and resize the landing
    $(window).on('resize', function(){

      startAnimation();
      resizeLanding();

    });



      //sizes the landing image and the icons
      function startAnimation() {


               $('.ey-col-svg').css('display', 'block');
               $('.areaSVG').css('display', 'inline-block');

              resizeLanding(); // resize the background image
          //    window.requestAnimationFrame(startAnimation);  //animate


     }  // end start Animation




    //resizes the landing image and sets top margin for the following section
    function resizeLanding() {

          var $lndFooter = $('#indexFooter');
          var $bgLand = $('#section0img');
          var $contactSection = $('#section2Div');
          var winHeight = $(window).height();
          var lndFooterHeight = $lndFooter.height();

          bgFinalHeight = winHeight - lndFooterHeight;
          $bgLand.css("height", bgFinalHeight);

          $contactSection.css("margin-top", bgFinalHeight);

      }



      // changes the .css classes depending on section, 
      //(also triggers landing image resize if necessary)
      function toggleIntroClass(){

          var winHeight = $(window).height();
          var heightThreshold = $("#section0").offset().top;
          var heightThreshold_end  = $("#section0").offset().top + $("#section0").height();

          $(window).scroll(function() {
              var scroll = $(window).scrollTop();



          //if  user hasn't scrolled past 100px/the first section, adjust classes
          if (scroll <= 100) 
              // (scroll >= heightThreshold && scroll <  heightThreshold_end ) 
              {
                    sectionIndex = 1;

                   $('#newHeader').removeClass('fixed');
                    $('#nameBoxIndexTop').removeClass('fixed');
                    $('#indexIconsContainer').removeClass('fixed');
                    $('#indexIconsList').removeClass('fixed');
                    $('#linkCell').removeClass('fixed');
                    $('#indexFooter').removeClass('fixed');
                    $('.ey-text-content').removeClass('fixed');
                    $('.ey-col-svg').removeClass('fixed');
                    $('.ey-col-1').removeClass('fixed');
                    $('.ey-row-scale').removeClass('fixed');
                    $('.ey-nav-bar').removeClass('fixed');
                    $('.areaSVG').attr("class", "areaSVG");     

              } 

          //else if they have scrolled past the first hundred pixels/first section, adjust classes
              else {
                    sectionIndex = 2;

                    $('#newHeader').addClass('fixed');
                    $('#nameBoxIndexTop').addClass('fixed');
                    $('#indexIconsContainer').addClass('fixed');
                    $('#indexIconsList').addClass('fixed');
                    $('#linkCell').addClass('fixed');
                    $('#indexFooter').addClass('fixed');
                    $('.ey-text-content').addClass('fixed');
                    $('.ey-col-svg').addClass('fixed');
                    $('.ey-col-1').addClass('fixed');
                    $('.ey-row-scale').addClass('fixed');
                    $('.ey-nav-bar').addClass('fixed');        
                    $('.areaSVG').attr("class", "areaSVG fixed");


          }

                 }); //end inner scroll Function


    };//end intro Class toggle function






});//end document ready

Любая помощь будет оценена! Спасибо!

Ответы

Ответ 1

У меня есть кросс-браузерное решение здесь: http://codepen.io/anon/pen/EgZzxo

Это не идеально: есть некоторые проблемы с меняющейся шириной, но на вопрос, на который вы отправили ответ, я верю. Чтобы устранить другие проблемы, вы должны посмотреть на css, чтобы увидеть, не изменяют ли некоторые элементы свойство display, что может испортить ваши переходы. Также исправление ширины должно помочь, чтобы они не зависели от размера текста - он изменится, когда текст станет меньше, так что положение других элементов изменится вместе с ним.

Основная проблема, с которой вы столкнулись, заключалась в том, что .ey-row-scale.fixed имел display: inline-block, а .ey-row.scale - нет. Это была одна вещь, которая нарушала переход. Другое было то, что переход должен быть определен в элементе svg, поэтому вместо:

.indexAnimateLand {
}

Мне пришлось делать:

.indexAnimateLand svg {
}

а затем это сработало. Не уверен точно, почему, но это может быть до inline svg, не наследуя стили правильно.

Я также добавил переходы к текстовым элементам и должен был распутать некоторые поля !important, которые вы там вложили.

В целом код можно было бы улучшить в нескольких областях:

  • Не смешивайте встроенный стиль с CSS-таблицами стилей, так как очень сложно понять, что происходит от того, где
  • Попытайтесь поместить общие классы в друг друга в файле css, чтобы было легче увидеть, в чем разница, когда вы добавляете .fixed класс, например
  • Различные устройства служат для разных целей. font-size не следует определять в vh как относительно размера экрана и может текст нечитабельный
  • Используйте !important экономно или лучше, не используйте вообще. Часто код может быть более чистым, если вы устраните проблемы, которые заставляют вас использовать !important в первую очередь

Ответ 2

Я думаю, что я сделал что-то приятное с анимацией вашего меню навигации.

Первое, что я сделал, это очистить код от всего, что выглядело неиспользованным... Очевидно, из-за нескольких предыдущих попыток.

Удаление неиспользуемых классов CSS и неиспользуемых js вроде "уменьшено" количество строк.
Я также переименовал некоторые из оставшихся классов с более значимыми именами...
Потому что я был потерян.

Мне удалось исправить "скачкообразный эффект" анимации (я начал с последний CodePen, который вы опубликовали в комментариях), чтобы сделать движение выглядят настоящими гладкими. Я в основном делал это с помощью CSS.

Результаты

Смотрите в CodePen и на моем сервере

Отличный результат:

  • Chrome 53
  • Opera 40
  • FireFox 49

Значки глаз на 30% ниже экрана:
    (но может выглядеть как предназначено!):

  • Safari для Windows 5.1.7
    Я не смог проверить его на Safari 10, так как у меня нет устройства Apple.
  • Браузер Samsung (Samsung Galaxy S3)

На самом деле тонкий "скачкообразный" эффект фонового изображения на:
    (при активации анимации)

  • Chrome для Android (Samsung Galaxy S3)

Плохие странности в анимации:
    (но как минимизированные, так и расширенные состояния в порядке)

  • Проводник 11 (я ненавижу IE!)




Для браузеров, которые не поддерживают блоки видовых экранов (vh, vw и т.д.), Такие как Safari для окон и браузер Samsung, я нашел Saabi, CSS polyfill, чтобы "почти" понять это правильно. Это не идеально, но реально близко.

Другие браузеры поддерживают блоки видовых экранов, включая IOS Safari 10.

Обратите внимание на, что есть ошибки, которые Saabi вызывает в консоли, которые я не исправил.
Я думаю, что результатом является Saabi, чтобы не полностью проанализировать файл CSS.
Но поскольку он почти исправляет некоторые браузеры, не затрагивая других (Saabi запускается только в том случае, если браузер не поддерживает единицы просмотра). Это достойно.
Я использовал его на своем сервере, но не мог на CodePen, потому что не нашел CDN.

Об IE...
Проблема возникает из-за чего-то другого (или плохого) поддерживаемого...
Я не понял, что.

Я тестировал js с JSHint и CSS с CSSLint.
Есть незначительные проблемы из-за вашего SVG в CSS checker.
Из-за этого есть и в валидатор разметки W3C.

Я предлагаю создавать PNG из вашего SVG, чтобы удалить эти ошибки.
Эти ошибки могут быть причиной устранения проблем с отображением в Safari для Windows и браузера Samsung. Сааби держится за что-то... И я думаю, что это могут быть ваши "Гласные значки" SVG.

Не стесняйтесь спрашивать о каких-либо изменениях, которые я сделал.
;)

HTML

<div id="whole">
    <div id="nav-panel" class="indexRow minimise-smooter">
        <!-- fancy icon footer -->
        <div id="nav-title" class="indexRow minimise-smooter">
            LINKS
        </div>
        <div class="nav-eyes minimise-smooter indexRow">
            <div class="indexAnimateLand indexRow">
                <div class="eye-outer-div indexRow">
                    <a class="eSVG areaAnchor indexRow" href="e.html">
                        <div class="eye-inner-div indexRow">
                            <svg class="SVG" x="0px" y="0px" viewBox="0 0 80 80" perserveAspectRatio="xMidYMid meet" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                <defs>
                                    <filter id="f1" x="0" y="0" width="200%" height="200%">
                                        <feOffset result="offOut" in="SourceAlpha" dx="3" dy="3" ></feOffset>
                                        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2" ></feGaussianBlur>
                                        <feBlend in="SourceGraphic" in2="blurOut" mode="normal" ></feBlend>
                                    </filter>
                                </defs><path id="circle-background" opacity="0.4196" fill="#FFFFFF" enable-background="new    " d="
                                    M4.193,37.492c0-18.987,15.419-34.38,34.44-34.38c19.021,0,34.439,15.393,34.439,34.38c0,18.987-15.418,34.381-34.439,34.381
                                    C19.613,71.873,4.193,56.48,4.193,37.492L4.193,37.492z" filter="url(#f1)" ></path>
                                <path id="sclera" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M11.41,38.895c27.619-31.029,41.313-9.542,49.646-2.012c-4.306,6.07-12.69,27.49-46.392,9.919c0,0-5.375-3.548-5.641-4.75
     C12.787,37.379,11.41,38.895,11.41,38.895z" ></path>
                                <ellipse id="iris" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" cx="38.196" cy="36.63" rx="16.202" ry="15.686" ></ellipse>
                                <ellipse id="pupil" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" cx="38.529" cy="36.954" rx="5.628" ry="5.449" ></ellipse>
                                <path id="eyelid" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M56.955,26.227c5.438,2.787,12.803,9.595,12.803,9.595s-2.338,3.235-5.677,2.588c-4.027,3.396-13.345,29.705-49.417,8.393
     c33.702,17.571,42.086-3.849,46.392-9.919c-8.333-7.53-22.026-29.018-49.646,2.012c0,0-2.94,1.806-4.112-1.456
     c-1.172-3.261,2.481-0.477,4.009-2.911c1.527-2.434,3.674-3.557,7.682-6.792c-4.008,0.646-7.348,3.558-7.348,3.558
     c10.521-10.835,31.379-17.498,53.107-4.205C64.748,27.089,59.404,26.119,56.955,26.227z" ></path>
                            </svg>
                        </div>
                        <div class="eye-text indexRow minimise-smooter">LINK 1</div>
                    </a>
                </div>
                <div class="eye-outer-div indexRow">
                    <a class="eSVG areaAnchor indexRow" href="e.html">
                        <div class="eye-inner-div indexRow">
                            <svg class="SVG" x="0px" y="0px" viewBox="0 0 80 80" perserveAspectRatio="xMidYMid meet" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                <defs>
                                    <filter id="f1" x="0" y="0" width="200%" height="200%">
                                        <feOffset result="offOut" in="SourceAlpha" dx="3" dy="3" ></feOffset>
                                        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2" ></feGaussianBlur>
                                        <feBlend in="SourceGraphic" in2="blurOut" mode="normal" ></feBlend>
                                    </filter>
                                </defs><path id="circle-background" opacity="0.4196" fill="#FFFFFF" enable-background="new    " d="
                                    M4.193,37.492c0-18.987,15.419-34.38,34.44-34.38c19.021,0,34.439,15.393,34.439,34.38c0,18.987-15.418,34.381-34.439,34.381
                                    C19.613,71.873,4.193,56.48,4.193,37.492L4.193,37.492z" filter="url(#f1)" ></path>
                                <path id="sclera" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M11.41,38.895c27.619-31.029,41.313-9.542,49.646-2.012c-4.306,6.07-12.69,27.49-46.392,9.919c0,0-5.375-3.548-5.641-4.75
     C12.787,37.379,11.41,38.895,11.41,38.895z" ></path>
                                <ellipse id="iris" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" cx="38.196" cy="36.63" rx="16.202" ry="15.686" ></ellipse>
                                <ellipse id="pupil" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" cx="38.529" cy="36.954" rx="5.628" ry="5.449" ></ellipse>
                                <path id="eyelid" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M56.955,26.227c5.438,2.787,12.803,9.595,12.803,9.595s-2.338,3.235-5.677,2.588c-4.027,3.396-13.345,29.705-49.417,8.393
     c33.702,17.571,42.086-3.849,46.392-9.919c-8.333-7.53-22.026-29.018-49.646,2.012c0,0-2.94,1.806-4.112-1.456
     c-1.172-3.261,2.481-0.477,4.009-2.911c1.527-2.434,3.674-3.557,7.682-6.792c-4.008,0.646-7.348,3.558-7.348,3.558
     c10.521-10.835,31.379-17.498,53.107-4.205C64.748,27.089,59.404,26.119,56.955,26.227z" ></path>
                            </svg>
                        </div>
                        <div class="eye-text indexRow minimise-smooter">LINK 2</div>
                    </a>
                </div>
                <div class="eye-outer-div indexRow">
                    <a class="eSVG areaAnchor indexRow" href="e.html">
                        <div class="eye-inner-div indexRow">
                            <svg class="SVG" x="0px" y="0px" viewBox="0 0 80 80" perserveAspectRatio="xMidYMid meet" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                <defs>
                                    <filter id="f1" x="0" y="0" width="200%" height="200%">
                                        <feOffset result="offOut" in="SourceAlpha" dx="3" dy="3" ></feOffset>
                                        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2" ></feGaussianBlur>
                                        <feBlend in="SourceGraphic" in2="blurOut" mode="normal" ></feBlend>
                                    </filter>
                                </defs><path id="circle-background" opacity="0.4196" fill="#FFFFFF" enable-background="new    " d="
                                    M4.193,37.492c0-18.987,15.419-34.38,34.44-34.38c19.021,0,34.439,15.393,34.439,34.38c0,18.987-15.418,34.381-34.439,34.381
                                    C19.613,71.873,4.193,56.48,4.193,37.492L4.193,37.492z" filter="url(#f1)" ></path>
                                <path id="sclera" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M11.41,38.895c27.619-31.029,41.313-9.542,49.646-2.012c-4.306,6.07-12.69,27.49-46.392,9.919c0,0-5.375-3.548-5.641-4.75
     C12.787,37.379,11.41,38.895,11.41,38.895z" ></path>
                                <ellipse id="iris" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" cx="38.196" cy="36.63" rx="16.202" ry="15.686" ></ellipse>
                                <ellipse id="pupil" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" cx="38.529" cy="36.954" rx="5.628" ry="5.449" ></ellipse>
                                <path id="eyelid" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M56.955,26.227c5.438,2.787,12.803,9.595,12.803,9.595s-2.338,3.235-5.677,2.588c-4.027,3.396-13.345,29.705-49.417,8.393
     c33.702,17.571,42.086-3.849,46.392-9.919c-8.333-7.53-22.026-29.018-49.646,2.012c0,0-2.94,1.806-4.112-1.456
     c-1.172-3.261,2.481-0.477,4.009-2.911c1.527-2.434,3.674-3.557,7.682-6.792c-4.008,0.646-7.348,3.558-7.348,3.558
     c10.521-10.835,31.379-17.498,53.107-4.205C64.748,27.089,59.404,26.119,56.955,26.227z" ></path>
                            </svg>
                        </div>
                        <div class="eye-text indexRow minimise-smooter">LINK 3</div>
                    </a>
                </div>
                <div class="eye-outer-div indexRow">
                    <a class="eSVG areaAnchor indexRow" href="e.html">
                        <div class="eye-inner-div indexRow">
                            <svg class="SVG" x="0px" y="0px" viewBox="0 0 80 80" perserveAspectRatio="xMidYMid meet" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                                <defs>
                                    <filter id="f1" x="0" y="0" width="200%" height="200%">
                                        <feOffset result="offOut" in="SourceAlpha" dx="3" dy="3" ></feOffset>
                                        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2" ></feGaussianBlur>
                                        <feBlend in="SourceGraphic" in2="blurOut" mode="normal" ></feBlend>
                                    </filter>
                                </defs><path id="circle-background" opacity="0.4196" fill="#FFFFFF" enable-background="new    " d="
                                    M4.193,37.492c0-18.987,15.419-34.38,34.44-34.38c19.021,0,34.439,15.393,34.439,34.38c0,18.987-15.418,34.381-34.439,34.381
                                    C19.613,71.873,4.193,56.48,4.193,37.492L4.193,37.492z" filter="url(#f1)" ></path>
                                <path id="sclera" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M11.41,38.895c27.619-31.029,41.313-9.542,49.646-2.012c-4.306,6.07-12.69,27.49-46.392,9.919c0,0-5.375-3.548-5.641-4.75
     C12.787,37.379,11.41,38.895,11.41,38.895z" ></path>
                                <ellipse id="iris" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" cx="38.196" cy="36.63" rx="16.202" ry="15.686" ></ellipse>
                                <ellipse id="pupil" class="fillWhite" fill-rule="evenodd" clip-rule="evenodd" cx="38.529" cy="36.954" rx="5.628" ry="5.449" ></ellipse>
                                <path id="eyelid" class="fillDark" fill-rule="evenodd" clip-rule="evenodd" stroke-width="0.25" stroke-miterlimit="8" d="
     M56.955,26.227c5.438,2.787,12.803,9.595,12.803,9.595s-2.338,3.235-5.677,2.588c-4.027,3.396-13.345,29.705-49.417,8.393
     c33.702,17.571,42.086-3.849,46.392-9.919c-8.333-7.53-22.026-29.018-49.646,2.012c0,0-2.94,1.806-4.112-1.456
     c-1.172-3.261,2.481-0.477,4.009-2.911c1.527-2.434,3.674-3.557,7.682-6.792c-4.008,0.646-7.348,3.558-7.348,3.558
     c10.521-10.835,31.379-17.498,53.107-4.205C64.748,27.089,59.404,26.119,56.955,26.227z" ></path>
                            </svg>
                        </div>
                        <div class="eye-text indexRow minimise-smooter">LINK 4</div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div id="fullpage">
        <article>
            <section id="section0">
                <!-- content inside of landing section  (except for icons) -->
                <div id="section0img">
                </div>
            </section>
            <section id="section2">
                <div id="section2Div">
                    <h1><a id="contact">Section 2</a></h1>
                </div>
            </section>
            <section id="section3">
                <h1>Section 3</h1>
            </section>
        </article>
    </div>
</div>

И добавьте часть, чтобы использовать polyfill:
(прямо над </body>)

<!-- Saabi -->
<div id="viewport-unit-tester" style="opacity:0; height:1px; width:50vw;"></div>
<script>
// test if the browser can handle viewport unit.
// If not, it load Saabi, a polyfill CSS viewport unit.
var elem = document.getElementById("viewport-unit-tester");
var width = parseInt(window.innerWidth / 2, 10);
var compStyle = parseInt((window.getComputedStyle ?
                          getComputedStyle(elem, null) :
                          elem.currentStyle).width, 10);
//console.log(width);
//console.log(compStyle);
if(!width==compStyle){
    console.log("This browser doesn't support viewport units.");
}else{
    console.log("This browser supports viewport units.");
}

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
</script>
<script src="saabi/tokenizer.js"></script>
<script src="saabi/parser.js"></script>
<script src="saabi/vminpoly.js"></script>

jQuery/JavaScript:

$(document).ready(function() {
    var sectionIndex = 1;

    startAnimation();   //includes resizing background image and resizing svgs
    toggleIntroClass();  //adds css depending on section of page


    // if the user resizes the window, run the animation again, and resize the landing
    $(window).on('resize', function(){
        startAnimation();
    });


    //sizes the landing image and the icons
    function startAnimation() {
        $('.eye-inner-div').css('display', 'block');
        $('.SVG').css('display', 'inline-block');
    }

    // changes the .css classes depending on section, 
    //(also triggers landing image resize if necessary)
    function toggleIntroClass(){

        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            //if  user hasn't scrolled past 100px/the first section, adjust classes
            if (scroll <= 100) {
                sectionIndex = 1;

                $('#nav-title').removeClass('minimised');
                $('#nav-panel').removeClass('minimised');
                $('.eye-text').removeClass('minimised');
                $('.eye-inner-div').removeClass('minimised');
                $('.eye-outer-div').removeClass('minimised');
                $('.nav-eyes').removeClass('minimised');
                $('.SVG').attr("class", "SVG");     
            } 

            //else if they have scrolled past the first hundred pixels/first section, adjust classes
            else {
                sectionIndex = 2;

                $('#nav-title').addClass('minimised');
                $('#nav-panel').addClass('minimised');
                $('.eye-text').addClass('minimised');
                $('.eye-inner-div').addClass('minimised');
                $('.eye-outer-div').addClass('minimised');
                $('.nav-eyes').addClass('minimised');        
                $('.SVG').attr("class", "SVG minimised");
            }
        }); //end inner scroll Function
    }//end intro Class toggle function
});//end document ready

CSS

* {
    padding: 0;
    margin: 0;
}
html,
body {
    margin: 0;
    padding: 0;
    height: auto;
    border: none;
    font-size: 100%;
}
h1 {
    text-align: center;
    font-size: 10vh;
    font-family: sans-serif;
}

/* ------------------------------------------------------------------------------------------------------------------------- Main sections */
#section0 {
    height:100vh;
}
#section2 {
    height:100vh;
    background-color:red;
}
#section3 {
    height:100vh;
    background-color:yellow;
}
#section0img {
    background: url('https://cdn.pbrd.co/images/cZIoMIenr.png') no-repeat;
    -webkit-background-size: 100vw 100vh;
    -moz-background-size: 100vw 100vh;
    -o-background-size: 100vw 100vh;
    background-size: 100vw 100vh;
    height:100vh;
}

/* ------------------------------------------------------------------------------------------------------------------------- Navigation panel */
#nav-panel {
    text-align: center;
    box-sizing: border-box;
    position: fixed;
    vertical-align: middle;
    bottom: 0;
    left: 0;
    z-index: 500;
    max-height: 33.33vh;
    width: 100%;
    border-top: 0.5vh solid Gray;
    border-bottom: 0.5vh solid Gray;
}
.nav-eyes {
    width: 100% !important;
    max-height: 33.33vh;
    overflow: hidden;
    text-align: center;
}
.indexRow {
    background-color: #FBFBFA;
}
#nav-title {
    max-height: 3.33vh;
    line-height: 3.33vh;
    font-size: 3.33vh;
    padding: 2vh;
}
.areaAnchor {
    text-decoration: none !important;
    text-align: center;
}
.eye-text {
    text-rendering: optimizeLegibility;
    display: block;
    text-align: center;
    white-space: nowrap;
    max-height: 8vh;
    line-height: 3.5vh;
    color: black;
    z-index: 100;
    font-size: 4vh;
    margin: 3vh 0 .5vh 0 !important;
}

/* ------------------------------------------------------------------------------------------------------------------------- SVG icons */
.eye-outer-div {
    text-align: center !important;
    width: 20%;
    /*height: 100%;*/
    margin: 0;
    padding: 0;
    display: inline-block;
}
.eye-inner-div {
    display: none;
    height: auto;
    text-align: center;
    box-sizing: border-box;
    padding: 0;
}
.SVG {
    display:none;
    max-height: 18vh;
    box-sizing: content-box;
    margin: 0;
    -webkit-animation: SVG 1s forwards;
    animation: SVG 1s forwards;
}
@-webkit-keyframes SVG {
    100% {
        max-height: 18vh;
    }
    0% {
        max-height: 9vh;
    }
}
@keyframes SVG {
    100% {
        max-height: 18vh;
    }
    0% {
        max-height: 9vh;
    }
}

/* ------------------------------------------------------------------------------------------------------------------------- minimised */
#nav-panel.minimised {
    border-top: 0px solid Gray;
    border-bottom: 0px solid Gray;
}
#nav-title.minimised {  /* SAME AS .eye-text.minimised */
    max-height: 0;
    font-size: 0;
    color: red;
    margin: 0;
    padding: 0;
    line-height: 0;
}
.nav-eyes.minimised {
    max-height: 9vh;
}
.eye-outer-div.minimised {
    width: 20%;
    max-height:9vh;
    padding: 0;
    margin: 0;
    display: inline-block;
    float: none;
    /*  box-sizing: border-box; */
}
.eye-text.minimised{
    max-height: 0;
    font-size: 0;
    color: red;
    margin: 0;
    padding: 0;
    line-height:0;
}
.SVG.minimised {
    -webkit-animation: SVGFixed 1s forwards;
    animation: SVGFixed 1s forwards;
}
@-webkit-keyframes SVGFixed {
    0% {
        max-height: 18vh;
    }
    100% {
        max-height: 9vh;
    }
}
@keyframes SVGFixed {
    0% {
        max-height: 18vh;
    }
    100% {
        max-height: 9vh;
    }
}
.minimise-smooter{
    -webkit-transition-property: line-height, font-size, max-height, color, padding, margin, border-bottom, border-top;
    -moz-transition-property: line-height, font-size, max-height, color, padding, margin, border-bottom, border-top;
    -o-transition-property: line-height, font-size, max-height, color, padding, margin, border-bottom, border-top;
    transition-property: line-height, font-size, max-height, color, padding, margin, border-bottom, border-top;
    -webkit-transition-duration: 1s;
    -moz-transition-duration: 1s;
    -o-transition-duration: 1s;
    transition-duration: 1s;
}
/* ------------------------------------------------------------------------------------------------------------------------- END of minimised */

/* ------------------------------------------------------------------------------------------------------------------------- SVG formatting for the eyes*/
#circle-background {
    -moz-filter: box-shadow(3px 3px 2px rgba(0, 0, 0, 0.5));
    -webkit-filter: box-shadow(3px 3px 2px rgba(0, 0, 0, 0.5));
    filter: box-shadow(3px 3px 2px rgb(0, 0, 0, 0.5));
    fill: Gainsboro;
}
.fillDark {
    fill: #939598;
}
.fillWhite {
    fill: White;
}
.active #circle-background-e,
.active #sclera,
.active #pupil {
    fill: rgb(183, 36, 103);
}
.active #eyelid,
.active #iris {
    stroke: rgb(183, 36, 103);
}
.active #eyelid,
.active #iris {
    fill: white;
}
.active #circle-background-s {
    fill: rgb(82, 79, 161);
}
.eSVG #pupil {
    fill: Black;
}

Ответ 3

http://codepen.io/stephendesjardins/pen/wzEVrQ

.ey-col-svg {
  height: auto;
  text-align: center;
  box-sizing: border-box;
  padding: 0;
  position:relative;
  height:100px;
  transition:height 0.3s;
}

.fixed .ey-col-svg {
  height:50px;
}

.fixed .ey-text-content {
  display:none;
}
/*this is the container for the  bottom svg */

.areaSVG {
  box-sizing: content-box;
  margin: 0;
  position:absolute;
  height:100%;
  width:100%;
  z-index:10;
  left:0;
  top:0;

}

Вы можете настроить его, но вот суть этого. Вместо того, чтобы делать высоту перехода на svg, сделайте это на родительском div. Кроме того, просто добавьте на него высоту и поместите в нее свой svg absolute. Я не понимаю, почему это должно быть динамическим с max-height. Значки и текст никогда не будут превышать высоту в этом конкретном примере.

Я надеюсь, что это поможет

Ответ 4

Пожалуйста, сделайте следующее в вашей ссылке (http://codepen.io/ihatecoding/pen/LREOPW):

  • Добавьте этот класс в свой CSS:

    .animated {transition: all .6s ease-in-out;}
    
  • Я редактировал код JS, который указан ниже. Не забудьте заменить этот блок "if else", начиная с строки 75 в вашей части js-кода codepen:

    if (scroll <= 100){
       sectionIndex = 1;
       $(".ey-col-1").css("transform","scale(1)");
    }else{
       sectionIndex = 2;
       $(".ey-col-1").addClass("animated").css("transform","scale(0.6)");
    }