2014-09-16 2 views
-2

약간의 질문이 있습니다. 나는 내 자신의 웹 사이트를 만들기 위해 바쁘다 :링크에서 빵 부스러기 만들기, 도움말?

HTML :

<nav> 
<ul class="menu"> 
    <li><a href="#home">HOME</a></li> 
    <li><a href="#about">ABOUT</a></li> 
    <li><a href="#portfolio">PORTFOLIO</a></li> 
    <li><a href="#contact">CONTACT</a></li> 
</ul> 
</nav> 

지금은 몇 가지 문제를 발견 한 가지입니다; 방문자가 사이트의 어느 부분을보고 있는지 알려주고 싶습니다.

예 :

링크를 마우스로 가리키면 검은 색 배경이 나타납니다. 하지만 그 특정 페이지에 오래 머물러있는 배경을 원합니다.

'연락처'를 클릭하면 해당 페이지에 머무르는 동안 검은 색 배경이 해당 링크에 표시됩니다.

+0

난 당신이 라우팅을위한 해시 태그를 활용 참조 왜 당신의 메뉴 배경을 설정뿐만 아니라 것을 사용할 수 없습니다. – Daniel

+0

자바 스크립트로 클래스를 추가하는 것은 어떨까요? –

+2

질문에 관련 코드를 게시하십시오 ([최소, 완전하고 검증 가능한 예제] (http://stackoverflow.com/help/mcve/)를 만드십시오). 귀하의 사이트에 링크 만하지 마십시오 (귀하의 문제가 해결되면 이후의 모든 사람들에게 그 의문이 무의미 해지기 때문에). –

답변

0

문서의 scroll 이벤트에 연결해야합니다. 내가 찾은 바이올린은 다음과 같습니다 : http://jsfiddle.net/cse_tushar/Dxtyu/141/.

스크롤하는 동안 onScroll 콜백은 현재 div을 확인합니다. 스크롤 바의 현재 위치 (어느 정도 - scrollPos)를 모든 div 컨테이너의 위치와 높이와 비교하여이를 수행합니다. 일치하는 항목이 있으면 메뉴의 링크에 특정 클래스 active을 추가합니다. 다른 모든 div의 경우 active 클래스가 제거됩니다.

JavaScript 코드에도 부드러운 스크롤이 포함되어 있지만 이미 구현되었으므로 무시할 수 있습니다.

0

오히려 간단한 방법은 다음과 같습니다

이처럼 CSS에 .active 클래스의 스타일을 정의합니다

.menu a:hover, 
.menu .active a { 
    color: #fff; 
    background-color: #000; 
    padding: 5px; 
} 

을 그리고 클릭 요소에 클래스를 토글 일부 자바 스크립트를 추가

$('.menu').on('click', 'a', function (event) { 
    event.preventDefault(); 
    $(this).parent().addClass('active').siblings().removeClass('active'); 
}); 

빠른 작동 예제는 fiddle을 참조하십시오.

2

같은 호버 스타일 활성 클래스를 만들고

당신의 CSS이 추가 다음과 같이 다른 링크를 클릭 할 때이 클릭에 링크 추가하고 스크롤을 변경하거나

.menu a.active { 
color: #fff; 
background-color: black; 
padding: 5px; 
} 

이 항목을 내 JS에 추가하십시오.

$(function(){ 
//onclick 
$('.menu a').click(function(){ 
$('.menu a').removeClass('active'); 
$(this).addClass('active'); 
}); 
//onscroll 
$(document).on("scroll", onScroll); 
}); 

function onScroll(event){ 
    var scrollPos = $(document).scrollTop(); 
    $('#menu-center a').each(function() { 
     var currLink = $(this); 
     var refElement = $(currLink.attr("href")); 
     if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { 
      $('#menu-center ul li a').removeClass("active"); 
      currLink.addClass("active"); 
     } 
     else{ 
      currLink.removeClass("active"); 
     } 
    }); 
} 
+0

이것은 나를 위해 일했습니다. 고마워요. – aDutchCow

+0

나는 그것이 기뻤다. 대답을 upvote하십시오. –

0

내 페이지에 코드가 있습니다. 두 가지 사소한 변화를 제안합니다. 라인 77에

편집 css.css 및 "활성"인 링크가 CSS 정의에 추가 선택을 추가 : 또한 스크립트를 수정해야합니다

.menu a:visited, 
.menu a.active{ 
    color: #fff; 
    background-color: black; 
} 

.사용자가이를 클릭 할 때 JS가 링크에 "활성"클래스를 전환하기 위해, 내가 의견을 추가 한 볼 :

$(function() { 
    $('[data-typer-targets]').typer(); 
}); 

$(function() { 
    $('a[href*=#]:not([href=#])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 

     // removes the active class from all the link in the menu 
     $('a', $(this).parent().parent()).toggleClass('active', false); 
     // adds the active class to the link that was clicked 
     $(this).toggleClass('active', true); 

     if (target.length) { 
     $('html,body').animate({ 
      scrollTop: target.offset().top 
     }, 1000); 
     return false; 
     } 
    } 
    }); 
}); 

나는이 도움이 괭이.

0

내가 .bullseye 당신이 섹션 (#home, # 정보, #portfolio, #contact)에 추가해야하는 클래스입니다 스크롤 기능

// On Scroll Change Nav 
    jQuery('.bullseye').waypoint(function(direction) { 
     var idThis = jQuery(this).attr('id'); 

     if(direction === 'down'){ 
      jQuery('a.scroll').removeClass('active'); 
      jQuery('a[href="#'+idThis+'"]').addClass('active'); 
      //console.log(idThis); 
     }   
    }, { offset: 75 }); 

    jQuery('.bullseye').waypoint(function(direction) { 
     var idThis = jQuery(this).attr('id'); 

     if(direction === 'up'){ 
      jQuery('a.scroll').removeClass('active'); 
      jQuery('a[href="#'+idThis+'"]').addClass('active'); 
      //console.log(idThis); 
     }   
    }, { offset: 'bottom-in-view' }); 

에 대한 웨이 포인트 http://imakewebthings.com/jquery-waypoints/를 사용하여 비슷한 만들었습니다. 다음

그리고

메뉴 모음에 대한

// Smooth Scroll 
    jQuery('a.scroll[href*=#]:not([href=#])').click(function() { 

     jQuery('a.scroll').removeClass('active');   
     var hrefMatch = jQuery(this).attr('href'); 

     jQuery('a[href="'+hrefMatch+'"]').addClass('active'); 

    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
     || location.hostname == this.hostname) { 

     var target = jQuery(this.hash);  
     target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']'); 
     if (target.length) { 
     jQuery('html,body').animate({ 
      scrollTop: target.offset().top - 75 
     }, 1000); 

     return false; 
     } 
    } 
    }); 

그리고 마지막 아니지만 적어도를 (당신이 메뉴 링크에 .scroll 클래스를 추가하거나 스크립트를 개조 할 필요)에서 클릭 이벤트에 대한 스크립트 활성 클래스는

.menu a.active{ 
color: #fff; 
background-color: black; 
padding: 5px; 
} 

작동합니다 그리고 기본적으로 그것 뿐이다 :) 당신이 :)이

0

내가 좋을 것 작업 할 경우에 저를 투표 :

$('ul.menu a').each(function() { 
    $(this).toggleClass('activePage', this.getAttribute('href') === window.location.hash); 
}); 

또는 간단하게는 :

$('a[href="' + window.location.hash + '"]').addClass('activePage');