简体   繁体   English

使用 jQuery 与页面上的其他元素接触时隐藏元素

[英]Hide an element when it touches other elements on the page with jQuery

I wanted to hide a sidebar element when it overlaps with the images on the page.当侧边栏元素与页面上的图像重叠时,我想隐藏它。 I found a great answer on StackOverflow, but it doesn't entirely solve my problem.我在 StackOverflow 上找到了一个很好的答案,但它并不能完全解决我的问题。 Right now, it only works with the first image on the page.目前,它仅适用于页面上的第一张图片。 It will hide the sidebar when it touches the first image.当它接触到第一张图片时,它会隐藏侧边栏。 But it won't hide for the rest of the images.但它不会隐藏图像的 rest。 What should I do if I want it to work with all the images on the page?如果我想让它与页面上的所有图像一起工作,我该怎么办?

Here is my code.这是我的代码。

function collision ($div1, $div2) {
  var x1 = $div1.offset().left
  var y1 = $div1.offset().top
  var h1 = $div1.outerHeight(true)
  var w1 = $div1.outerWidth(true)
  var b1 = y1 + h1
  var r1 = x1 + w1
  var x2 = $div2.offset().left
  var y2 = $div2.offset().top
  var h2 = $div2.outerHeight(true)
  var w2 = $div2.outerWidth(true)
  var b2 = y2 + h2
  var r2 = x2 + w2

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) {
    $div1.addClass('show')
  } else {
    $div1.removeClass('show')
  }
}

window.setInterval(function () {
  collision($('#content-nav'), $('.image-container'))
}, 100)

Here is how it's working right now.这是它现在的工作方式。 https://imgur.com/a/BvTyiDQ https://imgur.com/a/BvTyiDQ

What's happening is that you're calling only the first element with the image-container class, so it'll only check the topmost image-container.发生的事情是您只使用图像容器 class 调用第一个元素,因此它只会检查最顶层的图像容器。 You have to retrieve all instances of image-container and check against them for overlap.您必须检索图像容器的所有实例并检查它们是否重叠。

Here's what your collision function would look like & a working JSFiddle这是您的碰撞 function 的样子和工作的JSFiddle

 function collision ($nav) {
  var x1 = $nav.offset().left
  var y1 = $nav.offset().top
  var h1 = $nav.outerHeight(true)
  var w1 = $nav.outerWidth(true)
  var b1 = y1 + h1
  var r1 = x1 + w1
  var hide = false 

$(".image-container").each(function() {

  var x2 = $(this).offset().left
  var y2 = $(this).offset().top
  var h2 = $(this).outerHeight(true)
  var w2 = $(this).outerWidth(true)
  var b2 = y2 + h2
  var r2 = x2 + w2

    if (!(b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2)) {
    hide = true;
  }
});
  if (!hide) {
    $nav.removeClass('hide')
  } else {
    $nav.addClass('hide')
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM