2017-05-07 79 views
0

我想通過向左/向右箭頭(在keybord上)或鼠標中鍵滾動來滾動左側位置。 現在左邊的位置只在我向下/向上滾動時才起作用。Jquery- offsetLeft在滾動到右側時不起作用

我的劇本很簡單:

$(window).scroll(function() { 
var scroll = $(window).scrollTop(); 

if(scroll >= 672) { 
    $('.firm-row-th').addClass("stickyHeader"); 
}else { 
    $('.firm-row-th').removeClass("stickyHeader"); 
} 

if($('.stickyHeader')[0]) { 
    $('.stickyHeader').css({ 'left': -$('.firm-container').scrollLeft() + "px" }); 
} 
}); 

我的CSS:

.firm-container { 
margin-left: 0px; 
width: calc(100% - 8px); 
white-space: nowrap; 
border: 1px solid #222; 
overflow-x: auto; 
z-index: 10; 
position: absolute; 
background-color: #fff; 
} 
.firm-row { 
display: table; 
table-layout: fixed; 
} 
.firm-row-th { 
display: table; 
table-layout: fixed; 
} 

.stickyHeader { 
position: fixed; 
top:0; 
} 

我加入fiddle前。

只需在stickyheader開啓時嘗試向右滾動。你會看到stickyHeader沒有刷新。然後嘗試向下滾動 - stickyheader將刷新。

回答

1

這是因爲您只在收聽窗口上的滾動事件,該窗口會向上滾動,而不會滾動到左右滾動的.firm-container上。

更新您的JS是這樣的:

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

$('.firm-container').scroll(function() { 
    handleScroll(); 
}); 

function handleScroll() { 
var scroll = $(window).scrollTop(); 

    if(scroll >= 2) { 
    $('.firm-row-th').addClass("stickyHeader");//.css({ 'left': -$('.firmy-container').scrollLeft() + "px" }); 
    }else { 
    $('.firm-row-th').removeClass("stickyHeader"); 
    } 

    if($('.stickyHeader')[0]) 
    { 
    $('.stickyHeader').css({ 'left': -$('.firm-container').scrollLeft() + "px" }); 
    } 
} 

JS-小提琴:https://fiddle.jshell.net/j4v90rw4/2/

+0

哦......這麼簡單。謝謝 :) – Kafus