【问题标题】:changing background-color of a div responding to the position of the other divs根据其他 div 的位置更改 div 的背景颜色
【发布时间】:2023-03-19 08:21:01
【问题描述】:

我有以下代码

html

<div class="checker">
</div>
<div class="red boxes">
</div>
<div class="green boxes">
</div>
<div class="blue boxes">
</div>

css

.checker {
    width: 100px;
    height: 100px;
    border: 1px solid black; 
    position: fixed;
    top: 0;

}
.boxes {
    margin-top: 300px;
    width: 600px;
    height: 600px;
}
.red {
    background: red;
}
.green {
    background: green;
}
.blue {
    background: blue;
}

当类“.checker”通过滚动触摸“.checker”的底部边框时,如何使用jquery将“.checker”类的背景颜色更改为“.boxes”的背景颜色

例如:当 .class 红色到达 class=".red .checker" 的底部边框时,“.checker”类的背景颜色应该变为红色。等我不明白如何做到这一点。请帮帮我。

jsfiddle

【问题讨论】:

  • 三票赞成,没有任何 JavScript 被尝试过?

标签: jquery html css


【解决方案1】:

这个 jsFiddle 展示了如何检测重叠,您可以使用它并扩展来更改类。 http://jsfiddle.net/98sAG/

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

信用: jQuery Collision

【讨论】:

  • 非常感谢......我是 js 的新手......这对我很有帮助。
【解决方案2】:

你问的是这样的 http://jsfiddle.net/98sAG,如果你想在碰撞发生时尝试触发它,你可以使用 jQ 碰撞 API

【讨论】:

    【解决方案3】:

    也许这段代码会有所帮助:Efficiently Detect When Sibling Elements Overlap。

    您或许可以简化代码,只检查垂直位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2019-11-04
      • 2014-03-15
      相关资源
      最近更新 更多