【问题标题】:Change element class depending upon the position of the element根据元素的位置更改元素类
【发布时间】:2026-02-20 23:55:01
【问题描述】:

我对此有一些疑问。希望你能帮助我。

我在固定位置创建了菜单。我希望它可以更改我网站某些部分的颜色。

请看附件以更好地理解

其实我有一些代码:

我的切换菜单:

<input type="checkbox" id="toggle" class="input-toggler">   

<label for="toggle" class="menu-toggler">

        <span class="menu-toggler-line" id="change"></span>
        <span class="menu-toggler-line" id="change"></span>
        <span class="menu-toggler-line" id="change"></span>

</label>

此菜单的样式:

.menu-toggler{
    position: fixed; 
    right:5%; 
    top:10%;
    z-index: 9999; 
    display: flex; 
    justify-content:center; 
    flex-direction:column; 
    cursor: pointer;
}

.menu-toggler-line{
    height: 4px;
    width: 32px;
    display: block;
    background-color: $font--color;
    margin-bottom: 4px;
    transition: transform .2s ease, background-color .5s ease;
}

不幸的是,我无法编写任何有意义的 jquery 代码来处理这个解决方案......

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 网上有很多例子可以帮助你。您需要找到菜单的垂直位置以及滚动元素的垂直位置。当它们重叠时,改变样式。
  • 我找不到正确的轨道...你有例子吗?
  • 你能重新表述一下你的问题吗?
  • 我正在寻找一种解决方案,当它与其他元素重叠时,我可以在滚动时更改菜单的颜色。我希望我的菜单仅在此部分更改颜色...我正在寻找可以帮助我解决问题的方法。

标签: jquery html css scroll


【解决方案1】:

查看此代码:

var nav = $("#navbar").offset();
var $contentDivs = $(".division");
$(document).scroll(function() {
    $contentDivs.each(function(k) {
        var _thisOffset = $(this).offset();
        var _actPosition = _thisOffset.top - $(window).scrollTop();
        if (_actPosition < nav.top && _actPosition + $(this).height() > 0) {
            $("#navbar").removeClass("light dark").addClass($(this).hasClass("light") ? "light" : "dark");
            return false;
        }
    });
});
#navbar {
    position:fixed;
    top:10px;
    right:20px;
    height:100px;
}
#navbar.light {
    color:black;
}
#navbar.dark {
    color:white;
}
.division {
    width:100%;
    margin:0px;
    height:350px;
}
.division.dark {
    background:black;
}
.division.light {
    background:#f2f2f2;
}
<script src="https://use.fontawesome.com/ecdc7512a9.js"></script>
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
   
<div>
    <div id="navbar">
        <i class="fa fa-bars  fa-2x" aria-hidden="true"></i> 
        <span id="current"></span>
    </div>
    <div class="division light"></div>
    <div class="division dark"></div>
    <div class="division light"></div>
    <div class="division dark"></div>
    <div class="division light"></div>
    <div class="division dark"></div>
</div>

【讨论】: