当访问者在页面上的特定类时,使文本具有不同的颜色

时间:2014-05-30 17:19:10

标签: javascript jquery html css

我在侧边栏菜单(普通html)上浏览页面。例如:

<div class="sidebar"><h2>About us</h2>

<h3><a href="#chapter1" class="link">Chapter 1</a></h3>
<h3><a href="#chapter2" class="link">Chapter 2</a></h3>
<h3><a href="#chapter3"  class="link">Chapter 3</a></h3>
</div>

当访问者点击第1章时,他会转到第1章部分,侧边栏中的第1章链接会在几秒钟内呈现不同的颜色(因为:主动延迟)。

但是,这不是我案例的解决方案。当访问者在第1章部分时,我希望侧边栏中的链接颜色不同。 当访问者向下滚动到第2章时,第1章链接将返回正常,侧栏中的第2章链接将是不同的颜色。

欢迎提出解决方案/建议!

更新:我在本网站上使用Wordpress。 有一些很好的建议,但看起来他们不适合我。我使用基于Wordpress的网站,侧边栏是Wordpress侧边栏。 侧边栏有一个固定的位置。

3 个答案:

答案 0 :(得分:1)

为活动或非活动

添加样式
.active { color=red; }
.inactive { color=black; }

为您的章节添加onMouseOver =“setActive(1)”,onMouseOver =“setActive(2)”等等......

然后添加一个js函数来设置侧栏中的颜色。

function setActive(ch)
{
   document.getElementById("#chapter1").className="link "+(ch==1:"active";"inactive");
   document.getElementById("#chapter2").className="link "+(ch==2:"active";"inactive");
   document.getElementById("#chapter3").className="link "+(ch==3:"active";"inactive");
}

当您点击任何侧边栏元素时,您可能还想调用setActive(xx)。

答案 1 :(得分:0)

答案 2 :(得分:0)

Bootstrap有这个内置的,所以你可以使用他们的面包屑,

或者我用jquery组合了一个很好的小提琴:http://jsfiddle.net/8S2eu/2/

这是相关的脚本:

设置页面如下:

<div class="sidebar"><h2>About us</h2>

<h3><a href="#chapter1" class="link active" id="chapter1">Chapter 1</a></h3>
<h3><a href="#chapter2" class="link" id="chapter2">Chapter 2</a></h3>
<h3><a href="#chapter3"  class="link" id="chapter3">Chapter 3</a></h3>
</div>
<div class='main'>
    <section id="chapter1">
        <a id="chapter1"></a>
    </section>
    <section id="chapter2">
        <a id="chapter2"></a>
    </section>
    <section id="chapter3">
        <a id="chapter3"></a>
    </section>
</div>

运行它所需的JS:

$(".main").on("scroll",function(e){
    var fifty_percent_y = $(".main").height() * 0.5;
    var scroll_position = $(this).scrollTop();
    var prev_scroll_position = $(this).data('scroll_position');
    var delta = scroll_position - prev_scroll_position;
    $(this).data('scroll_position', scroll_position);


    //the rule is: if the top of chapter section tag crosses up across 50% then it becomes active, or if the bottom of a section tag crosses down across 50% then it becomes active.
    $('section').each(function(i, el){
        $this = $(this);
        var top_y = $this.position().top;
        var bottom_y = top_y + $this.height();
        if ((top_y     < fifty_percent_y && top_y    + delta > fifty_percent_y) ||
            (bottom_y  > fifty_percent_y && bottom_y + delta < fifty_percent_y)
           ){
            $("a").removeClass('active');
            $("a#" + $this[0].id).addClass('active');
            return false;
        }
    });
});