2016-08-05 80 views
1

我有一個水平滾動的div:的jQuery - 觸發事件,如果水平滾動的DIV是在最左邊和最右邊的滾動

<div id = "scrollable-div"> 
    <div class = "div-inside"></div> 
    <div class = "div-inside"></div> 
    <div class = "div-inside"></div> 
    <div class = "div-inside"></div> 
</div> 

我想觸發一個事件,當用戶滾動到div的最右側,然後是滾動到div最左側的另一個事件。我有以下的代碼,當我到了極點正確的觸發事件:

jQuery(function ($) { 
     $('#scrollable-div').on('scroll', function() { 
      if ($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) { 
       $('#end-treatment').show(); 

      } 
     }) 
    }); 

但我似乎無法得到回到左邊時,它的工作。基本上,我想在滾動到最右側時顯示一個div,而當滾動到最左側時顯示另一個div。這可能嗎?謝謝..

回答

2

是的,如果我正確理解你。看到下面的代碼片段,但基本思想是if($(this).scrollLeft() === 0) { ... }

我也插入邏輯(見我的評論),隱藏消息,以防萬一你想要的,但你可以刪除它,如果這不是你想要的。

jQuery(function ($) { 
 
    $('#div-1').on('scroll', function() { 
 
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) { 
 
     $('#end-treatment').show(); 
 
    } else if($(this).scrollLeft() === 0) { 
 
     $('#other-message').show(); 
 
     
 
    // Remove this part if you don't want your messages hidden again 
 
    } else { 
 
     $('#end-treatment').hide(); 
 
     $('#other-message').hide(); 
 
    } 
 
    }) 
 
});
.scrollable-div { 
 
    max-width: 200px; 
 
    overflow-x: auto; 
 
    white-space: nowrap; 
 
    background: lightgray; 
 
} 
 

 
.div-inside { 
 
    display: inline-block; 
 
    width: 100px; 
 
    height: 30px; 
 
    margin-top: 10px; 
 
    margin-bottom: 10px; 
 
    background: gray; 
 
} 
 

 
.message { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="div-1" class="scrollable-div"> 
 
    <div class="div-inside"></div> 
 
    <div class="div-inside"></div> 
 
    <div class="div-inside"></div> 
 
    <div class="div-inside"></div> 
 
</div> 
 

 
<div id="end-treatment" class="message"> 
 
    "End Treatment" 
 
</div> 
 

 
<div id="other-message" class="message"> 
 
    "Other Message" 
 
</div>

+0

PERFECTO!你贏了,非常感謝你的幫助! – Martin

+0

不客氣!很高興我能幫上忙 :) – BDawg