2014-01-22 3 views
0

다음 코드를 사용하여 스크롤 할 때 div를 페이지 상단으로 수정했습니다.스크롤 할 때 div를 수정하십시오.

$('.container').data("top", $('.container').offset().top); 

$(window).scroll(function(){ 
    if ($(window).scrollTop() > $('.container').data("top")) { 
     $('.container').css({'position': 'fixed', 'top': '0'}); 
    } 
    else { 
     $('.container').css({'position': 'static', 'top': 'auto'}); 
    } 
}); 

요소와 상위 CSS는 다음과 같습니다.

부모

.content-right { 
    width: 688px; 
    margin-top: 11px; 
    margin-right: 10px; 
    float: right; 
} 

.container { background: #FFF; background-color: #FFF; width: 687px; box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); margin-right: 10px; margin-bottom: 20px; } 

요소

하지만 페이지를 스크롤 할 때, 요소가 페이지 상단에 고정되지 않습니다. 어떻게이 문제를 해결할 수 있습니까?

업데이트

컨테이너는 일반적인 스타일입니다. 같은 스타일의 요소가 여러 개 있으며 원하는 요소를 식별하기 위해 클래스를 사용했습니다. 코드를이 코드로 변경했습니다.

바이올린Fiddle

+0

이해가 안가 - 당신이 .container라는 상단에 충실하려는 요소, 또는 .payment - 정보 - 컨테이너를한다? 귀하의 코드는 두 가지 모두를 나타내는 것 같지만 어느 것이 맞는지 확실하지 않습니다. –

+0

[Fiddle] (http://jsfiddle.net)과 같은 온라인 데모를 만들 수 있습니까? –

+0

가짜를 만드십시오 : jsfiddle.net –

답변

0

당신은 시도 할 수 있습니다 :

var $container = $('.payment-info-container'), 
    top = $container.offset().top + $container.outerHeight(); 

$(window).scroll(function(){ 
    if ($(window).scrollTop() > top) { 
     $container.css({'position': 'fixed', 'top': '0'}); 
    } else { 
     $container.css({'position': 'static', 'top': 'auto'}); 
    } 
}); 

DEMO를 참조하십시오. BTW, 바이올린에 jquery 리소스를로드하지 않았습니다.

0

시도 입니다.

JSFIDDLE

/* Dynamic top menu positioning 
* 
*/ 

var num = 50; //number of pixels before modifying styles 

$(window).bind('scroll', function() { 
    if ($(window).scrollTop() > num) { 
     $('.menu').addClass('fixed'); 
    } else { 
     $('.menu').removeClass('fixed'); 
    } 
}); 

//USE SCROLL WHEEL FOR THIS FIDDLE DEMO 
관련 문제