如何将 jQuery 文档准备好切换到视口中的元素?

How to switch jQuery document ready into element in viewport?

我想在我的网站中实现一个 CSS/jQuery 动画栏,但我不希望它在网站重新加载时加载。我希望它在进出视口时具有动画效果。我知道我还需要做一个动画来卸载,但是我想先触发加载动画。

我尝试了以下方法,但由于某种原因它没有响应。当 skillbar jquery 函数被插入到 window.scroll 之后的 checkanimation 函数中时,它在每次滚动时都有效,但是当直接移动到 checkanimation 函数并在父 div "kompetencje" 为在视口中它没有响应。

有什么建议吗?谢谢。

https://jsfiddle.net/mmsmsy/7zymr7zq/2/

function isElementInViewport(elem) {
var $elem = $(elem);

// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();

// Get the position of the element on the page.
var elemTop = Math.round( $elem.offset().top );
var elemBottom = elemTop + $elem.height();

return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('#kompetencje');

if (isElementInViewport($elem)) {
    // Start the animation
    jQuery('.skillbar').each(function(){
        jQuery(this).find('.skillbar-bar').animate({
            width:jQuery(this).attr('data-percent')
        },1000);
    });
}
}

您的 checkAnimation() 函数定义了两次,但操作不同,因此此代码段将第二个函数的内容移到第一个函数中并省略了第二个定义。

function isElementInViewport(elem) {
  var $elem = $(elem);

  // Get the scroll position of the page.
  var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
  var viewportTop = $(scrollElem).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  // Get the position of the element on the page.
  var elemTop = Math.round($elem.offset().top);
  var elemBottom = elemTop + $elem.height();

  return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
function checkAnimation() {

  // Affixing handler
  var window_top = $(window).scrollTop();
  var div_top = $(".junior").offset().top;
  var x = $(window).height();
  if (window_top > div_top) {
    $("ul.menusy").addClass("affixed");
  } else if (window_top < (div_top + x)) {
    $("ul.menusy").removeClass("affixed");
  }

  var $elem = $('#kompetencje');
  if (isElementInViewport($elem)) {
    // Start the animation
    jQuery('.skillbar').each(function() {
      jQuery(this).find('.skillbar-bar').animate({
        width: jQuery(this).attr('data-percent')
      }, 1000);
    });
  } else {
    jQuery('.skillbar-bar').stop(true,false).width(0);
  }
}

// Capture scroll events
$(window).scroll(function() {
  checkAnimation();

});

$(document).on('click', 'a[href^="#"]', function(e) {
  // target element id
  var id = $(this).attr('href');

  // target element
  var $id = $(id);
  if ($id.length === 0) {
    return;
  }

  // prevent standard hash navigation (avoid blinking in IE)
  e.preventDefault();

  // top position relative to the document
  var pos = $id.offset().top - 100;

  // animated top scrolling
  $('body, html').animate({
    scrollTop: pos
  }, 200);

});


// Unified scroll listener
/*
$(function() {
   $(window).scroll(checkAnimation);
   checkAnimation();
});
*/
@media only screen and (max-width: 1100px) {
    /* For mobile phones: */
    [class*="col-"] {
        width: 100%;
    }
}
@font-face {
    font-family: "Specify Font";
    src: url(fonts/specify/SpecifyPERSONAL-ExExpMedium.ttf);}
@font-face {
    font-family: "Theano Font";
    src: url(fonts/theano/TheanoOldStyle-Regular.ttf);}
@font-face {
    font-family: "Kayak Font";
    src: url(fonts/kayak/KayakSansRegular.otf);}
@font-face {
    font-family: "Kayak Font";
    src: url(fonts/kayak/KayakSansBold.otf);
    font-weight: bold;}
@font-face {
    font-family: "Adam Font";
    src: url(fonts/adam/ADAMCGPRO.otf);}
html,
body {
 background: #edefee; /* For browsers that do not support gradients */
 background: -webkit-linear-gradient(-45deg, #edefee, #eaeceb); /* For Safari 5.1 to 6.0 */
 background: -o-linear-gradient(-45deg, #edefee, #eaeceb); /* For Opera 11.1 to 12.0 */
 background: -moz-linear-gradient(-45deg, #edefee, #eaeceb); /* For Firefox 3.6 to 15 */
 background: linear-gradient(-45deg, #edefee, #eaeceb); /* Standard syntax */
 color: rgb(25,25,25);
 font-family: "Kayak Font";
 font-size: 18px;
 overflow-x: hidden;
 padding: 0;
 margin: 0;}
a:link,
a:visited,
a:hover,
a:active {
 color: black;
 text-decoration: none;
 -webkit-transition: all .15s;
 transition: all .15s;}
a:hover {
 color: rgb(200,200,200);}
#naglowek {
 width: 100vw;
 height: 200px;
 background: #596476;
 overflow: hidden;
 padding: 0;
 border-left: 2px solid #596476;
 border-bottom: 1px solid rgb(25,25,25);
 margin: 0;
 margin-bottom: 50px;}
h1 {
 width: 850px;
 min-width: 850px;
 color: #fbfbfd;
 font-family: "Adam Font";
 font-size: 50px;
 line-height: 54px;
 text-align: center;
 border-bottom: 1px solid #fbfbfd;
 margin: 48px auto 12px auto;}
h2 {
 width: 780px;
 min-width: 780px;
 color: #fbfbfd;
 font-family: "Kayak Font";
 font-size: 24px;
 text-align: center;
 margin: 0 auto 24px auto;}
ul.menusy {
 display: block;
 width: 750px;
 min-width: 750px;
 height: 32px;
 background: #596476;
 font-family: "Kayak Font";
 font-size: 24px;
 list-style: none;
 overflow: hidden;
 padding: 0;
 padding-top: 1px;
 margin: 0 auto;}
ul.menusy.affixed {
    z-index: 10000;
    margin-left: -375px;
    position: fixed; top: 0; left: 50%;}
#naglowek li{
 display: inline;
 padding: 0;
 margin: 0;}
#naglowek li a {
 background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(transparent 50%, #677689 51%, #677689 100%);
    background-size: 200%;
    color: #fbfbfd;
 padding: 6px 15px;
 -webkit-transition: all .2s;
 transition: all .2s;}
#naglowek li a:hover {
 background-position: 0 100%;}
#glowneMenu {
 display: block;
 font-family: "Kayak Font";
 float: left;
 overflow: hidden;
 padding: 0;
 border-left: 2px solid #596476;
 margin: 0;}
#glowneMenu img {
 padding: 0;
 margin: 0 auto 3vw auto;}
.zdjecie {
 display: block;
 width: 50%;
 min-width: 235px;
 padding: 0;
 border-radius: 100%;}
#kontakt {
 width: 100%;
 display: block;
 margin: 0 auto;}
#kontakt p {
 font-size: 24px;
 text-align: center;}
#kontakt i {
 color: #596476;
 font-size: 54px;
 margin: 3vh 0 0 0;}
.kontakt {
 font-size: 32px;
 font-weight: bold;
 padding: 0 120px 0 120px;
 border-bottom: 1px solid rgb(25,25,25);
 margin: 0;}
#tresc {
 color: rgb(25,25,25);
 display: block;
 float: right;
 font-size: 24px;
 text-align: justify;
 overflow: hidden;
 padding: 0 4vw;
 border-left: 2px solid #596476;
 margin: 0;
 margin-bottom: 50px;}
#tresc h1 {
 width: auto;
 color: rgb(25,25,25);
 font-size: 28px;
 line-height: 32px;
 text-align: left;
 padding: 0;
 border-bottom: 1px solid black;
 margin: 0;
 margin-bottom: 24px;}
#zacznijtu {
 display: block;
 width: 100%;
 min-height: 90vh;}
.zacznijtu {
 padding: 0 8vw;}
#wyksztalcenie {
 display: block;
 width: 100%;
 min-height: 90vh;
 margin: 0;}
ul.punktowanie {
 list-style: none;
 padding: 0 8vw;}
summary {
 font-size: 30px;
 font-weight: bold;
 outline: none;}
@keyframes fadeInDown {
    0% {
        opacity: 0;
        transform: translateY(-1em);
    }
    100% {
        opacity: 1;
        transform: translateY(0);
    }
}
details[open] > p {
    animation-name: fadeInDown;
    animation-duration: 0.5s;}
#kompetencje {
 display: block;
 width: 100%;
 min-height: 90vh;
 margin: 0;}
table {
 width: 100%;}
.skillbar {
 position:relative;
 display:block;
 margin-bottom:15px;
 width:100%;
 background:gainsboro;
 height:35px;
 border-radius:3px;
 -moz-border-radius:3px;
 -webkit-border-radius:3px;
 -webkit-transition:0.4s linear;
 -moz-transition:0.4s linear;
 -ms-transition:0.4s linear;
 -o-transition:0.4s linear;
 transition:0.4s linear;
 -webkit-transition-property:width, background-color;
 -moz-transition-property:width, background-color;
 -ms-transition-property:width, background-color;
 -o-transition-property:width, background-color;
 transition-property:width, background-color;
}

.skillbar-title {
 position:absolute;
 top:0;
 left:0;
width:110px;
 font-weight:bold;
 font-size:13px;
 color:#ffffff;
 background:#6adcfa;
 -webkit-border-top-left-radius:3px;
 -webkit-border-bottom-left-radius:4px;
 -moz-border-radius-topleft:3px;
 -moz-border-radius-bottomleft:3px;
 border-top-left-radius:3px;
 border-bottom-left-radius:3px;
}

.skillbar-title span {
 display:block;
 background:rgba(0, 0, 0, 0.1);
 padding:0 20px;
 height:35px;
 line-height:35px;
 -webkit-border-top-left-radius:3px;
 -webkit-border-bottom-left-radius:3px;
 -moz-border-radius-topleft:3px;
 -moz-border-radius-bottomleft:3px;
 border-top-left-radius:3px;
 border-bottom-left-radius:3px;
}

.skillbar-bar {
 height:35px;
 width:0px;
 background:#6adcfa;
 border-radius:3px;
 -moz-border-radius:3px;
 -webkit-border-radius:3px;
}

.skill-bar-percent {
 position:absolute;
 right:10px;
 top:0;
 font-size:11px;
 height:35px;
 line-height:35px;
 color:#ffffff;
 color:rgba(0, 0, 0, 0.4);
}
#doswiadczenie {
 display: block;
 width: 100%;
 min-height: 40vh;
 margin: 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body>
 <div id="naglowek">
  <h1>MATEUSZ SEBASTIAN MYSIAK</h1>
  <h2 class="junior">Junior Front-End Developer</h2>
  <ul class="menusy">
   <li><a href="#naglowek">Zacznij tu</a></li>
   <li><a href="#wyksztalcenie">Wykształcenie</a></li>
   <li><a href="#kompetencje">Kompetencje</a></li>
   <li><a href="#doswiadczenie">Doświadczenie</a></li>
   <li><a href="#kontakt">Kontakt</a></li>
  </ul>
 </div>
 <div class="container-fluid">
  <div class="row">
   <div id="tresc" class="col-xs-9">
    <div id="zacznijtu">
     <h1>O MNIE</h1>
     <p class="zacznijtu">
      Mam na imię Mateusz i zajmuję się Web Development od 2010 roku, kiedy stworzyłem swoją pierwszą, prowizoryczną stronę. Z zawodu jestem inżynierem sieci i systemów komputerowych w małych i średnich firmach, ale ze względu na to jak fascynuje mnie programowanie i jego nieskończone możliwości, zmieniam profesję. Od czasów moich pierwszych kroków wykonałem niezliczone ilości własnych stron i zleceń klientów. Szukam pracy w zespole, dzięki któremu mógłbym dużo szybciej się rozwinąć.
     </p>
    </div>
    <div id="wyksztalcenie">
     <h1>WYKSZTAŁCENIE</h1>
     <p class="wyksztalcenie">
      <ul class="punktowanie">
       <li>
        <details>
          <summary>II Liceum Ogólnokształcące im. Piotra Firleja w Lubartowie (2007-2010)</summary>
          <p>Profil: <strong>matematyczno-fizyczno-informatyczny</strong>,</p>
          <p>przedmiotów rozszerzone: matematyka, fizyka, informatyka, j. angielski.</p>
        </details>
       </li>
       <li>
        <details>
          <summary>Matura (2010)</summary>
          <p>matematyka - 96%,</p>
          <p>fizyka rozszerzona - 50%,</p>
          <p>j. polski - 40%,</p>
          <p>j. angielski - 100%,</p>
          <p>j. angielski rozszerzony - 90%.</p>
        </details>
       </li>
       <li>
        <details>
          <summary>Wojskowa Akademia Techniczna w Warszawie (2010-2011)</summary>
          <p>Kierunek: <strong>Informatyka</strong>.</p>
          <p>Nie ukończyłem ze względu na prace związane z opracowaniem obudowy <a href="#enclosuresMobile">Enclosures Mobile Future</a>.</p>
        </details>
       </li>
       <li>
        <details>
          <summary>Uniwersytet Marii-Curie Skłodowskiej w Lublinie (2011-2013)</summary>
          <p>Kierunek: <strong>Filozofia</strong>.</p>
          <p>Nie ukończyłem ze względu na otwarcie firmy <a href="#enclosuresMobile">Enclosures Mobile</a>.</p>
        </details>
       </li>
       <li>
        <details>
          <summary>Cambridge Certificate of Proficiency in English, CPE (2014)</summary>
        </details>
       </li>
       <li></li>
       <li></li>
       <li></li>
      </ul>
     </p>
    </div>
    <div id="kompetencje">
     <h1>KOMPETENCJE</h1>
     <table>
      <tr>
       <td><strong>Techniczne</strong></td><td><strong>Ogólne</strong></td>
      </tr>
      <tr>
       <td>
        <div class="skillbar clearfix " data-percent="75%">
         <div class="skillbar-title" style="background: gray;"><span>HTML5</span></div>
         <div class="skillbar-bar" style="background: #999;"></div>
         <div class="skill-bar-percent">80%</div>
        </div> <!-- Koniec Paska Umiejetności -->
       </td>
      </tr>
      <tr>
       <td>
        <div class="skillbar clearfix " data-percent="75%">
         <div class="skillbar-title" style="background: gray;"><span>CSS3</span></div>
         <div class="skillbar-bar" style="background: #999;"></div>
         <div class="skill-bar-percent">80%</div>
        </div> <!-- Koniec Paska Umiejetności -->
       </td>
      </tr>
     </table>
    </div>
    <div id="doswiadczenie">
     <h1>DOŚWIADCZENIE</h1>
    </div>
   </div>
   <div id="glowneMenu" class="col-xs-3">
    <img class="zdjecie" src="zdjecie.jpg" title="zdjecie.jpg"/>
    <div id="kontakt">
     <p>
      <span class="kontakt">KONTAKT</span><br />
      <i class="glyphicon glyphicon-phone"></i><br />
      (+48) 799-981-252<br />
      <a href="mailto:someone@example.com?Subject=Hello%20again" target="_top">mmsmsy@gmail.com</a><br />
     <br />
      <i class="glyphicon glyphicon-globe"></i><br />
      <a href="http://www.mmsmsy.com" target="_blank">mmsmsy.com</a>
     </p>
    </div>
   </div>
  </div>
 </div>
 
 <script src="scrollAnim.js"></script>
</body>