如何使用 JQuery 按类和 id 选择非父元素

How to select non-parent elements by class and id with JQuery?

本文关键字:选择 元素 id 何使用 JQuery      更新时间:2023-09-26

>我需要通过id和类使用JQuery函数选择元素。问题是元素不是父母。像这样说:

<div class="image"></div>
<div id="contact"></div>

我的代码正在工作,但这不是解决方案。

$(document).ready(function() {
$(window).scroll(function() {
    $('.featurette-image').each(function() {
        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        if( bottom_of_window > bottom_of_object ) {
            $(this).animate({'opacity':'1'}, 700);
        }
    });
    $("#contactme").each(function() {
        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        if( bottom_of_window > bottom_of_object ) {
            $(this).animate({'opacity':'1'}, 500);
        }
    });
});

});

提前谢谢。

您可以使用

逗号,加入jquery选择器,如下所示:

$("#contactme, .featurette-image").each(...

此行为在其文档中进行了描述:https://api.jquery.com/multiple-selector/

也许这个:

$("#contactme, .featurette-image").each(function() {
  var bottom_of_object = $(this).offset().top + $(this).outerHeight();
  var bottom_of_window = $(window).scrollTop() + $(window).height();
  if( bottom_of_window > bottom_of_object ) {
     $(this).animate({'opacity':'1'}, 700);
  }
});

$(document).ready(function() {
  $(window).scroll(function() {
    $('body div').each(function() {
       if ($(this).hasClass('featurette-image') || $(this).attr('id') == 'contact') {
        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        if( bottom_of_window > bottom_of_object ) {
            $(this).animate({'opacity':'1'}, 700);
        }
      }
    });

  });
});