웹 페이지 포지셔닝 내비게이션 사례 (js 방법)

2952 단어
js 방법


// getByClassName , class name 

   function hasClass( obj, cls ){ 
        return obj.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
    }
    
    function removeClass( obj, cls ){ 
        if( hasClass( obj, cls )){ 
            //remove
            var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
            obj.className = obj.className.replace(reg, "");
        }
    }

    function addClass(obj , cls ){
          if( !hasClass( obj, cls )){ 
            //remove
    
            obj.className += " "+ cls;
        }
    }
    
    
    // getByClassName , class 
    
    function getByClassName(obj , cls){
       var elements = obj.getElementsByTagName("*");
       var result = [];
       for (var i = 0; i< elements.length; i++) {
          if (elements[i].className == cls){
            result.push(elements[i])
          }
       }
       return result
    }
    
    function getScrollTop() {  
            var scrollPos;  
            if (window.pageYOffset) {  
            scrollPos = window.pageYOffset; }  
            else if (document.compatMode && document.compatMode != 'BackCompat')  
            { scrollPos = document.documentElement.scrollTop; }  
            else if (document.body) { scrollPos = document.body.scrollTop; }   
            return scrollPos;   
    }  
  
    window.onload = function(){ 

        
        window.onscroll = function(){   
             //      
            // var top = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
           
             var top=getScrollTop()
             // console.log(top)
            var menus = document.getElementById("menu").getElementsByTagName("a");
            // var items = document.getElementById("content").getElementByClassName("item")
            
            var items = getByClassName(document.getElementById("content"), "item");
            
            var currentId = "";
            
            for ( var i=0; i< items.length; i++ ){ 
                var _item = items[i];
                var _itemTop = _item.offsetTop;
                console.log(_itemTop)
                if( top > _itemTop - 200 ){ 
                    //  jq #, 
                    currentId = _item.id;
                } else { 
                    break;
                }           
            }
        
                            
      // , menu a class current
           if(currentId){
             for( var j = 0 ; j < menus.length ; j++){
                var _menu = menus[j];
                var _href = _menu.href.split("#");
// , id , 
                if (_href[_href.length - 1] != currentId) {
                  removeClass(_menu,"current");
                }else{
                  addClass(_menu,"current");
                }


             }
           }
      
    
        }   
    }   
  
                

좋은 웹페이지 즐겨찾기