滚动上的淡入元素

FadeIn elements on scroll

本文关键字:元素 淡入 滚动      更新时间:2023-09-26

>我有一个函数,目前,它会按顺序淡入元素,但 id 就像鼠标滚轮一样,如果可能的话,可以控制它们的不透明度。

任何人都可以建议我如何做到这一点吗?它是否需要鼠标滚轮插件?感谢您的任何输入

http://jsfiddle.net/gLtgj54s/

$('.sector-link').each(function (i) {
    $(this).delay(350 * i).fadeIn(800);
});

网页标记

<div style="overflow:scroll;width:100%; border:0; height:300px; ">
            <div style="height:3000px; position:relative;">
                <div style="position:fixed;left:0; top:50px;">
                     sector links...
                  </div>
              </div>
          </div>

一种方法是可以使用数据属性来设置元素应淡入的点。

<div class="sector-link" data-scroll-point="100">Link 1</div>

在JS中检查scrollTop值何时在元素的滚动点和下一个元素的滚动点之间的范围内。

var arr = [];
$('.sector-link').each(function(i) {
  arr.push($(this).data("scroll-point"));
});
$(window).scroll(function() {
  var scrollTop = $(window).scrollTop();
  elementFade(scrollTop);
});
elementFade = function(top) {
  for (var i = 0; i < arr.length; i++) {
    var min = arr[i];
    var max = i != (arr.length - 1) ? arr[i + 1] : (arr[i] + 100);
    if (top >= min && top < max) {
      $('[data-scroll-point="' + arr[i] + '"]').fadeIn(800);
      $('p.info').html($('[data-scroll-point="' + arr[i] + '"]').html() + " visible at point " + arr[i]);
    }
  }
}
body {
  height: 3000px;
}
p.info {
  position: fixed;
  top: 0;
  font-size: 11px;
  color: #555;
  background: #eee;
  padding: 3px;
}
.sector-link {
  float: left;
  margin: 5px;
  padding: 5px;
  border-radius: 2px;
  background: #abcdef;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="info">Not visible</p>
<div style="position:fixed;left:0; top:50px;">
  <div class="sector-link" data-scroll-point="100">Link 1</div>
  <div class="sector-link" data-scroll-point="300">Link 2</div>
  <div class="sector-link" data-scroll-point="500">Link 3</div>
  <div class="sector-link" data-scroll-point="700">Link 4</div>
  <div class="sector-link" data-scroll-point="1000">Link 5</div>
  <div class="sector-link" data-scroll-point="1200">Link 6</div>
  <div class="sector-link" data-scroll-point="2000">Link 7</div>
  <div class="sector-link" data-scroll-point="2500">Link 8</div>
</div>

更新的小提琴

每当使用鼠标滚轮滚动时,不透明度都会发生变化,使其或多或少可见。这是使用 DOMMouseScroll 事件或mousewheel事件。请参阅以下代码:

function moveObject(event){
    var delta=0;
    if(!event)event=window.event;
    if(event.wheelDelta){
        delta=event.wheelDelta/600;
    }else if(event.detail){
        delta=-event.detail/20;
    }
    var target = $('body > div');
    var adj = parseFloat(target.css('opacity'));
    target.css('opacity',Math.max(0,Math.min(1,adj+Math.max(0.6,adj)*delta)));
}
if(window.addEventListener){
    document.addEventListener('DOMMouseScroll',moveObject,false);
}else{
    document.onmousewheel=moveObject;
}

这里有一个jsFiddle可以自己尝试一下:http://jsfiddle.net/gLtgj54s/14/

感谢:http://viralpatel.net/blogs/javascript-mouse-scroll-event-down-example/

你可以使用一个库,即scrollReveal.js,这非常好。

这是我使用库制作的代码笔。此代码笔的简化

您的代码可以像以下那样简单:

<html>
  <body>
      <p data-scrollreveal='ease in 50px'> Thing </p>
      <p data-scrollreveal='ease in 50px'> Thing </p>
      <p data-scrollreveal='ease in 50px'> Thing </p>
      ...
  </body>
</html>

https://github.com/julianlloyd/scrollReveal.js

由于 Apple 决定在完成滚动之前不发送"滚动"事件,我建议这样的东西 -

首先将所有内容设置为显示:块,不透明度:0

var scrollTop;
var $elements = $(...);
window.setTimeout(function(){ // Better to use requestAnimationFrame if available
    if (scrollTop !== window.scrollTop) {
        scrollTop = window.scrollTop;
        for (var i=0; i<elements.length; i++) {
            var rect = elements[i].getBoundingClientRect();
            elements[i].style.opacity = Math.min(1, Math.max(0, rect.top, rect.bottom > 0 ? window.innerHeight - rect.bottom : 0) / 20);
            // ie, Put in something to control it based on the difference between the top/bottom of the element and the display
        }
    }
}, 50);

尽管这是一个jQuery问题 - 在事物变化的每个帧上运行这样的代码可能会很昂贵,因此我使用了直接DOM代码,这要快得多!

这是一个修改的小提琴。 您的问题并不完全清楚,但我假设您希望根据元素在视口中的位置设置不透明度。

$(document).ready(function () {
    $('.sector-pink').css({
        opacity: 0,
        visibility: 'visible'
    });
    var setOpacity = function () {
        var container = $(this);
        $('.sector-link').each(function () {
            var self = $(this);
            var fromBottom = container.height() - self.offset().top;

            var opacity = fromBottom / 100;
            //100 is a magic number that will control how far from the bottom of the viewport things become fully visible.
            self.find('span').text(opacity.toFixed(2));
            self.css({
                'opacity': opacity
            });

        });
    };
    $('#container').scroll(function () {
        setOpacity();
    });
    setOpacity();
});
如果我

理解正确,您希望当用户向下滚动页面时,元素会按顺序淡入。(运行代码片段以查看这是否是您想要的(

var showing = false;
$(document).scroll(function() {
  if (!showing && isElementInViewport($('.sector-link:last'))) {
    showing = true;
    $('.sector-link').each(function(i) {
      $(this)
        .delay(100 * i)
        .css('visibility', 'visible')
        .hide()
        .fadeIn(400);
    });
  }
})
// This function determines if the given element is inside the current view port
function isElementInViewport(el) {
  //special bonus for those using jQuery
  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ );
}
body {
  height: 100000px;
}
.sector-link {
  font-size: x-small;
  visibility: hidden;
  border: 1px solid yellowgreen;
  padding: 0.1em;
  width: 120px;
  text-align: center;
  color: white;
}
div.placeholder {
  text-align: center;
  padding: 0.1em;
  height: 500px;
  width: 120px;
  background: yellowgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="placeholder">Scroll down slowly</div>
<div>
  <div class="sector-link" style="background:#563895">THING</div>
  <div class="sector-link" style="background:#765835">THING</div>
  <div class="sector-link" style="background:#068865">THING</div>
  <div class="sector-link" style="background:#a468f5">THING</div>
  <div class="sector-link" style="background:#56ffab">THING</div>
  <div class="sector-link" style="background:#563895">THING</div>
  <div class="sector-link" style="background:#8f68f5">THING</div>
  <div class="sector-link" style="background:#a6b8f5">THING</div>
</div>

  1. 这是你需要的吗?

    小提琴

    var cpt = 0;
    $( window ).scroll(function() {
       $('.sector-link:eq('+cpt+')').fadeIn(800);
       cpt = cpt + 1;
    });
    

    我删除了 jsfiddle 上的 delay(350(,但如果需要 : JsFiddle

  2. 我不知道你是否需要它,但如果需要,有一些代码 JsFiddle(不完美(可以做你想要的,反之亦然

    • 向下滚动时:您的事物一个接一个地出现
    • 向上滚动:你的东西一个接一个地消失

你可以简单地使用Twitter Bootstrap的Scrol Spy,而不是试图重新发明轮子。要使用它实现所需的行为,只需按照说明并添加以下 css:

.active ~ li {
    opacity: 0;
    transition: 1s;
}

顺便说一句,您也可以在那里尝试一下。打开链接的网站,在控制台上添加代码段,然后滚动浏览文档。

所以这是我对这个问题的解决方案:

具有 .sectrol 链接类的项目会根据滚动方式逐个淡出或逐个淡出。

为了使此方法起作用,您不必具有实际的滚动条。该解决方案不会跟踪滚动位置,而是基于"滚轮"事件。

它还会在向上滚动时淡出元素。

我相信您可以调整解决方案以满足您的需求。

   // Constants
var pxPerItem = 720;
var sectorLinks = $('.sector-link');
var scrollYMax = sectorLinks.length * pxPerItem;
//Fade controller variable
var currentScrollY = 0;

//Calculates fade value for the item based on current 'scroll' position
function calculateFade(itemNo) {
    var relativeScroll = (currentScrollY - pxPerItem * itemNo) / pxPerItem;
    return Math.min(Math.max(0, relativeScroll), 1)
}
//Keeps the controller scroll variable within the bounds based on the amount of elements. 
function normalizeCurrentScroll() {
    currentScrollY = Math.min(Math.max(0, currentScrollY), scrollYMax);
}
//The actual event that controls items fade
$(window).bind('mousewheel DOMMouseScroll', function(event){
    var delta = event.originalEvent.wheelDelta == 0 ? event.originalEvent.detail : event.originalEvent.wheelDelta;
    currentScrollY -= delta;
    for (var i = 0; i < sectorLinks.length; i++) {
        $(sectorLinks[i]).fadeTo(20, calculateFade(i));
    }    
    normalizeCurrentScroll();
});

淡入或淡出链接所需的滚轮滚动量由"pxPerItem"变量控制。如果你想把这样的东西放在页面下面的某个地方,你必须调整scrollYMax变量并计算FadeFunction,使它们与你的身高相匹配。

小提琴:https://jsfiddle.net/gLtgj54s/18/

我已经成功地使用它来完成您想要做的事情:

$(window).bind("scroll", function() {  
    if ($(this).scrollTop() > 800) { //Fade in at a level of height
        $(".XX").fadeIn("fast");  
        checkOffset(); //Call function
    } else {  
        $(".XX").stop().fadeOut("fast");  
    }  
});  
function checkOffset() {  
    if ($('.XX').offset().top + 500 + $('#myDiv').height() >= $('.Container').offset().top) {  
        $(".XX").stop().fadeOut("fast");
    }  
    if ($(window).scrollTop() + $(window).height() < $('.Container').offset().top) {  
        $('.XX').css('position', 'fixed'); //Restore when you scroll up  
    }  
}

我已经更新了你的小提琴,希望这就是你要找的?

这仅根据滚动位置对每个元素使用 .fadeIn/.fadeOut

例如:

if ( $(document).scrollTop() > 50 ) {
    $('#2').fadeIn(800);     
} else {
    $('#2').fadeOut(800); 
}