2017-06-15 62 views
0

我很努力地找出如何檢測固定位置的div何時開始並完成在滾動時懸停某個div。當固定位置的div跨越另一個元素時檢測

我有一個div總是固定在我的窗口並居中。當我滾動我的頁面時,我希望固定div在開始懸停另一個時更改其顏色,並在完成懸停後移除顏色。我附上了一個小模式來說明我的問題。要恢復:

當頁面加載具有黑色時的固定div - >開始懸停第二個div,顏色變成白色 - >完成將鼠標懸停在第二個div上,顏色返回黑色。

我發現這個問題:Detect when a position: fixed; element crosses over another element

當DIV開始跨越第二個,但是當懸停完成後不恢復顏色它的工作原理。我的代碼:

$(window).scroll(function() { 
    if ($('div.fixed').offset().top < ($(".div-to-cross").offset().top - 0)) { 
    $('div.fixed').removeClass('white'); 
    } else { 
    $('div.fixed').addClass('white'); 
    } 
}); 

在此先感謝您的幫助。

View image

回答

1

你必須採取的股利高度帳戶。

有兩個「時刻」來計算,進入和離開。

因此,當固定格的底部進入滾動的頂部...
而當滾動的底部離開固定的頂部。

這裏是運行一個例子:

$(window).scroll(function(){ 
 
    var fixed = $("div.fixed"); 
 
    
 
    var fixed_position = $("div.fixed").offset().top; 
 
    var fixed_height = $("div.fixed").height(); 
 

 
    var toCross_position = $(".div-to-cross").offset().top; 
 
    var toCross_height = $(".div-to-cross").height(); 
 

 
    if (fixed_position + fixed_height < toCross_position) { 
 
    fixed.removeClass('white'); 
 
    } else if (fixed_position > toCross_position + toCross_height) { 
 
    fixed.removeClass('white'); 
 
    } else { 
 
    fixed.addClass('white'); 
 
    } 
 

 
});
.fixed{ 
 
    position:fixed; 
 
    top:calc(50% - 50px); 
 
    left:0; 
 
    background-color:black; 
 
    height:100px; 
 
    width:100%; 
 
} 
 
.white{ 
 
    background-color:white; 
 
} 
 
.div-to-cross{ 
 
    height:100px; 
 
    background-color:blue; 
 
} 
 

 
/* just for this demo */ 
 
.spacer{ 
 
    height:400px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="fixed"></div> 
 
<div class="spacer"></div> 
 
<div class="div-to-cross"></div> 
 
<div class="spacer"></div>

+0

非常感謝你,它的工作原理就像一個魅力! 但是,我網站上的網頁並不需要訣竅來切換顏色,因爲固定div沒有此部分交叉,並且會導致我的其他javascript失效。你知道我們如何解決這個衝突嗎? –

+0

我想我找到了解決方案,我在IF語句中包含整個函數: 'if($('。div-to-cross')。length){做點什麼}' –

+0

是的......這就是。當然,如果沒有「div-to-cross」元素......可能會有問題。你的IF聲明應該有效。 –

相關問題