jquery - 到达 div 时更改 ul 样式(滚动)

标签 jquery css html scroll

我想在滚动时更改 ul 样式并使用 jQuery 到达 div,解释如下。

CSS:

#menu {
    background-color:#ccc;
    position:fixed;
    width:100%;
}

.menutext {
    padding:25 40 30 !important;
    display:inline-block;
}

.menutext2 {
    padding:25 40 0 !important;
    display:inline-block;
    color:red;
}

.alldivs {
    width:300px;
    height:200px;
    background-color:a9a9a9;
}

HTML代码:

<div id="menu">
    <div class="menutext">Change the style of me to .mebutext2 on arriving to DIV1</div>
    <div class="menutext">Change the style of me to .mebutext2 on arriving to DIV2</div>
    <div class="menutext">Change the style of me to .mebutext2 on arriving to DIV3</div>
</div>

<br><br><br>

<div class="alldivs"><div id="DIV1">DIV1</div></div>
<br><br><br><br>
<div class="alldivs"><div id="DIV2">DIV2</div></div>
<br><br><br><br>
<div class="alldivs"><div id="DIV3">DIV3</div></div>
<br><br><br><br>

我想在滚动并到达 div 顶部时将类“menutext”的 div 更改为类“menutext2”(第一个 ul 的类从 menutext1 更改为 menutext2 到达具有 id DIV1 的 div,第二个ul 的类在到达 ID 为 DIV2 的 div 时从 menytext1 更改为 menutext2,并且第一个 ul 的类按原样返回 menutext1,依此类推。

最佳答案

这应该可以满足您的要求,仅使用 jQuery:

$(document).scroll(function(e) {
    var detectrange = 50; //how close to the top of the screen does it need to get
    var scrolltop = $(window).scrollTop() + detectrange;
    $('.alldivs').each(function(i, el){
        if (scrolltop > $(el).offset().top) {
            $('.'+el.id).removeClass('menutext').addClass('menutext2');
        }
    });
});

请注意,为了使其正常工作,我必须在您的 div1div2div3 上应用 alldivs 类> 等,并赋予其 ID 对应的菜单项类。

这个 jsFiddle 中的演示:http://jsfiddle.net/ss7YF/

编辑 如果您只想突出显示最接近的菜单(我猜是为了固定菜单?),请使用此命令:

$(document).scroll(function(e) {
    var scrolltop = $(window).scrollTop();
    var mindist = 1000;
    var closest = '';
    $('.alldivs').each(function(i, el){
        var thisdist = Math.abs(scrolltop - $(el).offset().top);
        if (thisdist < mindist) {
            closest = el.id;
            mindist = thisdist;
        }
    });
    if (closest != '') {
        $('.menutext2').toggleClass('menutext menutext2');
        $('.'+closest).toggleClass('menutext menutext2');
    }
});

jsFiddle:http://jsfiddle.net/ss7YF/1/

关于jquery - 到达 div 时更改 ul 样式(滚动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801530/

相关文章:

html - 设置主页图像布局的样式 - 目标 div 或 img?

html - DIV 背景图像在智能手机上不是 100%

javascript - JavaScript 中的.text 冲突

html - 在按钮 div 之后获取随机链接

IE 7/8 的 CSS 帮助

html - 两列,固定流体,100% 高度

html - 在 css 中使用 ttf 文件

javascript - jQuery - 库还是框架?

javascript - jQuery 不透明动画不起作用,但任何其他动画都起作用

javascript - 在 Qualtrics 中跟踪外部链接被点击的时间?