jquery更改活动类固定div

时间:2016-05-05 00:42:58

标签: javascript jquery html css parent-child

我是使用JQuery和Javascript的新手。我无法弄清楚这里有什么问题。

我想将h1元素显示为块,并将该类添加为活动,因为父div正在窗口中显示。

我希望后续效果有点像这个网站上的'Y徽标'http://www.collectif-yay.com/en

HTML

<div class= "section" id="Title">
        <h1 style="position: fixed; top: 10px; display: none">Title</h1>
    </div>

    <div id="Publications">
        <h1 style="position: fixed; top: 10px; display: none">Publications</h1>
    </div>


    <div class= "section" id="Articles">
        <h1 style="position: fixed; top: 10px; display: none">Articles</h1>
    </div>


    <div class= "section" id="Contributors">
        <h1 style="position: fixed; top: 10px; display: none">Contributors</h1>
    </div>


    <div class= "section" id="Process">
        <h1 style="position: fixed; top: 10px; display: none">Process</h1>
    </div>

CSS

    div{
        height: 400px;
        display: block;
        width: 100%;
        padding: 10px;
        border: 0;
        overflow: hidden;
    }

    h1 {
        top: 10px;
        padding-left: 20px;
        width: 100%;
        color: #0000aa;
    }


    .section {
      padding-top: 100px;
      padding-bottom: 0px; 
    }

    .active {
      color: #0000aa; 

JQuery的

        $(document).ready(function () {
      setup_section_titles();
      display_section_titles();

    });


    $(window).scroll(function () { 
      display_section_titles();
    });


    function setup_section_titles() {
      $("h1").css("position", "fixed").css("top", "10px");
    }


    // ----------------------------------------
    function display_section_titles() {
      var sectionArray = $.makeArray($(".section"));

      var window_scroll_top = $(window).scrollTop();
      var window_center = $(window).height()/2;
      window_center = 100;

      // sort sections by their relative distance to the center of the window
      sectionArray.sort( function(a, b) { 
        return getDiff(a, window_scroll_top, window_center) > getDiff(b, window_scroll_top, window_center) ? 1 : -1; 
      });

      $(".section h1:visible").hide();
      $(sectionArray[0]).children("h1").show();

      $(".active").removeClass("active");
      $(sectionArray[0]).addClass("active");

    }

    // ----------------------------------------
    function getDiff(item, window_scroll_top, window_center) {
      var item_viewportoffset_top = $(item).offset().top - window_scroll_top;

      var dist_of_top = Math.abs(item_viewportoffset_top - window_center);
      var dist_of_bottom = Math.abs(item_viewportoffset_top + $(item).height() - window_center);

      // return minimum of distances of top and bottom of an element
      // to center of the window
      return Math.min( dist_of_top, dist_of_bottom );
    }

0 个答案:

没有答案