当元素出现在屏幕上时触发 jquery 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3045852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:48:02  来源:igfitidea点击:

Triggering jquery event when an element appears on screen

jquery

提问by agente_secreto

I want to show a fade effect as soon as the element appears on screen. There is a lot of content before this element so if I trigger the efect on document.ready, at certain resolutions the vistors wont′t see it.

我想在元素出现在屏幕上时立即显示淡入淡出效果。这个元素之前有很多内容,所以如果我在 document.ready 上触发效果,在某些分辨率下,访问者不会看到它。

Is it possible to trigger an event when, after scrolling down, the element becomes visible? I am almost sure I have seen this effect before, but have no idea how to achieve it.

当向下滚动后,元素变得可见时是否可以触发事件?我几乎可以肯定我以前见过这种效果,但不知道如何实现它。

Thank you!

谢谢!

采纳答案by Fedir RYKHTIK

jQuery Waypoints plugin could be useful. It provides a way to trigger an action when an element becomes visible on the screen.

jQuery Waypoints 插件可能很有用。它提供了一种在元素在屏幕上可见时触发操作的方法。

For instance:

例如:

$('.entry').waypoint(function() {
   alert('The element has appeared on the screen.');
});

There are some examples on the site of the plugin.

插件站点上有一些示例。

回答by fdrv

This one works better for me then the others in this post: http://www.teamdf.com/web/jquery-element-onscreen-visibility/194/

这个对我来说比这篇文章中的其他人更好:http: //www.teamdf.com/web/jquery-element-onscreen-visibility/194/

Usage is simple:

用法很简单:

$('#element').visible()

You can see how this plugin is used to create your effect here:

您可以在此处查看此插件如何用于创建效果:

http://css-tricks.com/slide-in-as-you-scroll-down-boxes/

http://css-tricks.com/slide-in-as-you-scroll-down-boxes/

function viewable() {
    $(".module").each(function(i, el) {
        var el = $(el);
        if (el.visible(true)) {
            el.addClass("come-in");
        });
    }
$(window).scroll(function() {
    viewable();
});
$(window).blur(function() {
    viewable();
});

If u use tabs. (for example jQuery UI tabs) you must check if tab is active.

如果你使用标签。(例如 jQuery UI 选项卡)您必须检查选项卡是否处于活动状态。

$(window).scroll(function() {
    if($('#tab-1').hasClass('active')) {
        viewable();
    }
});

回答by mineroot

Jquery.appear pluginis the best way to solve this problem.

Jquery.appear 插件是解决这个问题的最好方法。

demo.

演示.

回答by Aurora

If you want a simple and working sollution:

如果您想要一个简单且有效的解决方案:

function elementInView(elem){
  return $(window).scrollTop() < $(elem).offset().top + $(elem).height() ;
};

$(window).scroll(function(){
  if (elementInView($('#your-element')))
  //fire at will!
    console.log('there it is, wooooohooooo!');
});

回答by James Sumners

A quick search turned up this viewportextension for jQuery that will allow you to check an element's visibility in the viewport. If your element is not in the viewport, don't do your fade-in animation.

快速搜索为 jQuery 找到了这个视口扩展,它允许您检查元素在视口中的可见性。如果您的元素不在视口中,请不要执行淡入动画。

回答by S Pangborn

I think you're referring to the jQuery plugin "Lazy Load": http://www.appelsiini.net/2007/9/lazy-load-images-jquery-plugin

我认为您指的是 jQuery 插件“延迟加载”:http: //www.appelsiini.net/2007/9/lazy-load-images-jquery-plugin

From looking at the source code, it looks like the plugin is doing something like this:

从源代码来看,插件看起来像这样:

$('#item').one('appear', function () {
    // Do stuff here
});

回答by UncaughtTypeError

If you're looking to fire an event when a specified, or target, element scrollsinto view, you can do this by determining the following values:

如果您希望在指定或目标元素滚动到视图中时触发事件,您可以通过确定以下值来实现:

  1. the window height
  2. the scroll distance value from the top of the window
  3. the specified, or target, element's distance from the top of the window
  1. 窗口高度
  2. 距窗口顶部的滚动距离值
  3. 指定或目标元素距窗口顶部的距离

Consider the following:

考虑以下:

jQuery(window).on('scroll', function(){

    var elValFromTop = Math.ceil(jQuery('.target-el').offset().top),
        windowHeight = jQuery(window).height(),
        windowScrollValFromTop = jQuery(this).scrollTop();

   // if the sum of the window height and scroll distance from the top is greater than the target element's distance from the top, it should be in view and the event should fire, otherwise reverse any previously applied methods
   if ((windowHeight + windowScrollValFromTop) > elValFromTop) {
        console.log('element is in view!');
        jQuery('.target-el').addClass('el-is-visible');
   } else {
        jQuery('.target-el').removeClass('el-is-visible');
   }

});

Code Snippet Demonstration:

代码片段演示:

The below snippet demonstrates a working example of a common issue: fixing an element to the viewport when a specified element scrolls into view.

下面的代码片段演示了一个常见问题的工作示例:当指定元素滚动到视图中时,将元素固定到视口。

/* Sticky element on-scroll */
jQuery(window).on('scroll', function(){

    var elValFromTop = Math.ceil(jQuery('.target-el').offset().top),
        elHeight = jQuery('.target-el').outerHeight(),
        windowHeight = jQuery(window).height(),
        windowScrollValFromTop = jQuery(this).scrollTop(),
        headerHeightOffset = jQuery('.fixed-header').outerHeight();
        
   if ((windowHeight + windowScrollValFromTop) > elValFromTop) {
        console.log('element is in view!');
        console.log(headerHeightOffset);
        jQuery('.will-change-el').addClass('fixed-el').css('top',headerHeightOffset).text('fixed');
   } else {
        jQuery('.will-change-el').removeClass('fixed-el').css('top','0').text('static');
   }
   
   // using template literals for multi-line output formatting
   // comment out to observe when target element comes into view
   console.log(`
        how far is the target element from the top of the window: ${elValFromTop}
        what is the target element's height: ${elHeight}
        what is the window height: ${windowHeight}
        what is the window's scroll value distance from the top: ${windowScrollValFromTop}
        what is the sum of the window height and its offset value from the top: ${windowHeight + windowScrollValFromTop}
        `);
        
});
/* || Reset & Defaults */
body {
  margin: 0;
}

* {
  box-sizing: border-box;
  font-family: arial;
}

/* || General */
.target-el {
  border-top: 1px solid #ccc;
}

.target-el,
.will-change-el {
  transition: .7s;
  text-align: center;
  background: #ededed;
  border-bottom: 1px solid #ccc;
}

.fixed-el {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
}

.fixed-header {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  height: 100px;
  text-align: center;
  background: #ededed;
  border-bottom: 1px solid #ccc;
  z-index: 9;
}

.buffer-el {
  height: 1000px;
  padding-top: 100px;
  background: whitesmoke;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fixed-header">
  <h1>Fixed Header</h1>
</div>
<div class="buffer-el">
  <div class="will-change-el">static</div>
</div>
<div class="target-el">the target element</div>

Sandbox Example:CodePen

沙盒示例:CodePen

NOTE:
This will only apply to scroll actions on the document and not to any nested elements contained within a scroll view pane.

注意:
这仅适用于文档上的滚动操作,不适用于滚动视图窗格中包含的任何嵌套元素。