我不能让我的Javascript使用我的文本

时间:2018-01-24 22:24:32

标签: javascript

我通过滚动浏览了图片中幻灯片的这个javascript代码,但我想将其应用到我的文本中,但我无法弄清楚如何。

Html代码:

<p class="align-right slide-in">
hoi

</p>
<p class="align-left slide-in">


hoi
</p>
<p class="align-right slide-in">hoi</p>

CSS代码

    .slide-in {
      opacity:0;
      transition:all .5s;
    }

    .align-left.slide-in {
      transform:translateX(-30%) scale(0.95);
    }
    .align-right.slide-in {
      transform:translateX(30%) scale(0.95);
    }

    .slide-in.active {
      opacity:1;
      transform:translateX(0%) scale(1);
    }
.slide-in.active {
      opacity:1;
      transform:translateX(0%) scale(1);
    }

我从javascript 30天的挑战中偷走了大部分脚本。它是在图片中滑动但我想将其应用到我的文本

 <script>
        function debounce(func, wait = 20, immediate = true) {
          var timeout;
          return function() {
            var context = this, args = arguments;
            var later = function() {
              timeout = null;
              if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
          };
        };

        var sliderImages = document.querySelectorAll('.slide-in');

    function checkSlide() {
      sliderImages.forEach(sliderImage => {
        // half way through the image
        const slideInAt = (window.scrollY + window.innerHeight) - sliderImage.height / 2;
        // bottom of the image
        const imageBottom = sliderImage.offsetTop + sliderImage.height;
        const isHalfShown = slideInAt > sliderImage.offsetTop;
        const isNotScrolledPast = window.scrollY < imageBottom;
        if (isHalfShown && isNotScrolledPast) {
          sliderImage.classList.add('active');
        } else {
          sliderImage.classList.remove('active');
        }
      });
    }

    window.addEventListener('scroll', debounce(checkSlide));

1 个答案:

答案 0 :(得分:0)

您的网页需要足够大才能触发滚动事件。您还需要更改checkSlide中的逻辑以使用p元素。以下是转换工作的JSFiddle示例:

https://jsfiddle.net/3uf07s5n/

function checkSlide() {
      sliderImages.forEach(sliderImage => {

          sliderImage.classList.add('active');
          // You need to figure out when to add and remove the active class
          // sliderImage.classList.remove('active');
      });
    }