简体   繁体   English

想要在滚动到特定元素时更改导航颜色

[英]Wanting to change nav colour when scrolled to a specific element

I want to change the navigation bar colour when the 'main' section of my site is scrolled to. 当我的网站的“主要”部分滚动到时,我想更改导航栏的颜色。

At the moment I have it changing colour but not at that specific section. 目前,我正在改变颜色,但在该特定部分没有。 It needs to change at that section due to the responsive design of the site. 由于网站的响应式设计,因此需要在该部分进行更改。

Here is a basic jsfiddle example: http://jsfiddle.net/Forresty/8ottpo6x/1/ 这是一个基本的jsfiddle示例: http : //jsfiddle.net/Forresty/8ottpo6x/1/

Here is the code: 这是代码:

HTML: HTML:

<nav class="test"></nav>
<div class="someText">
    <p>......</p>
</div>
<main></main>

css: CSS:

nav {
    position: fixed;
    width: 100%;
    top: 0;
    height: 4.5em;
    background: black;
}

.main{
    width: 400px;
    height: 2000px;
    background: gray;
}

.black{
    background: red;
}

Javascript: 使用Javascript:

$(window).scroll (function () {
    var target = $(this).scrollTop();
        if (target >= 500) {
            $('nav').addClass('black');
        }else {
            $('nav').removeClass('black');
        }
    });

I tried the following javascript also: 我也尝试了以下javascript:

var main = $('main');

$(window).scroll (function () {
    var target = $(this).scrollTop();
        if (target >= main) {
            $('nav').addClass('black');
        }else {
            $('nav').removeClass('black');
        }
    });

This didn't work at all. 这根本没有用。

Any help would be highly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

You can get the offset of element by $('element').offset().top . 您可以通过$('element').offset().top获取$('element').offset().top https://api.jquery.com/offset/ https://api.jquery.com/offset/

http://jsfiddle.net/1vy7ocjz/1/ http://jsfiddle.net/1vy7ocjz/1/

var $window = $(window);
var $main = $('main');
var $nav = $('nav');
$window.scroll(function () {
    var target = $window.scrollTop();
    if (target >= $main.offset().top) {
        $nav.addClass('black');
    } else {
        $nav.removeClass('black');
    }
});

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

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