当特定div可见时改变颜色

14
请告诉我如何以最正确的方式完成这件事。
HTML:
<div id="fixed-red" class="fixed-red"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="red"></div>
<div id="green" class="green"></div>
<div id="blue" class="blue"></div>

CSS:

html,body{
  height:100%;
}
.fixed-red,.fixed-green,.fixed-blue{
  width:30px;
  height:30px;
  position:fixed;
  top:10px;
  left:10px;
  background:#333;
}
.fixed-green{
  top:50px;
}
.fixed-blue{
  top:90px;
}
.red-active{
  background:#f00;
}
.green-active{
  background:#0f0;
}
.blue-active{
  background:#00f;
}
.red,.green,.blue{
  width:100%;
  height:100%;
}
.red{
  background:#900;
}
.green{
  background:#090;
}
.blue{
  background:#009;
}

我希望能够在用户打开/关闭红色绿色, 或 蓝色 div(当它们可见时)时,向 fixed-red/green/blue div 中添加/删除红/绿/蓝-active 类,这样当用户访问它们时 ,小的 div 会分别以大的显示div的颜色进行高亮。

谢谢!


我想在大的红色、绿色和蓝色div上添加事件on,但我不知道如何检查它们是否可见。 - user7362793
对于现代浏览器,请参见-https://dev59.com/6nVD5IYBdhLWcg3wAGeD - user305883
1个回答

21

我必须微调代码使其更加 D.R.Y.。

现在类被 color 类取代。

$.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('resize scroll', function() {
  $('.color').each(function() {
      var activeColor = $(this).attr('id');
    if ($(this).isInViewport()) {
      $('#fixed-' + activeColor).addClass(activeColor + '-active');
    } else {
      $('#fixed-' + activeColor).removeClass(activeColor + '-active');
    }
  });
});
html,
body {
  height: 100%;
}

.fixed-red,
.fixed-green,
.fixed-blue {
  width: 30px;
  height: 30px;
  position: fixed;
  top: 10px;
  left: 10px;
  background: #333;
}

.fixed-green {
  top: 50px;
}

.fixed-blue {
  top: 90px;
}

.red-active {
  background: #f00;
}

.green-active {
  background: #0f0;
}

.blue-active {
  background: #00f;
}

.color {
  width: 100%;
  height: 100%;
}

#red {
  background: #900;
}

#green {
  background: #090;
}

#blue {
  background: #009;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fixed-red" class="fixed-red red-active"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="color"></div>
<div id="green" class="color"></div>
<div id="blue" class="color"></div>

这是一个可用的fiddle示例:

https://jsfiddle.net/BoyWithSilverWings/ds9x55z7/


谢谢您的回答,但我怀疑人们会使用hover来做这种事情。 - user7362793
我想你可以使用 mouseenter mouseleave 事件。您可以查看示例 https://jsfiddle.net/BoyWithSilverWings/ds9x55z7/1/ (但那实际上是悬停功能)。 - Agney
谢谢,但我认为这不是使用鼠标完成的方式。我可以考虑使用scrollTop来检查元素的高度,但不确定这是否是正确的方法以及如何实现。 - user7362793
我认为你可能指的是https://dev59.com/bGIi5IYBdhLWcg3w9gNy#33979503。 - Agney
非常感谢你,拥有银翼的男孩! - user7362793
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接