根据滚动位置隐藏和显示导航箭头

时间:2016-01-22 15:32:36

标签: javascript jquery

我有一个水平列表,其中有箭头可以浏览它,我正试图让右箭头在到达末尾时消失(左箭头也是如此)。这是有效的......有点像。我的问题是需要额外的点击才能使它们消失,即使它之前的点击将到达列表的末尾。任何建议将不胜感激!

JsFiddle link

//Hide left at start
$('#lefty').hide();
//left arrow controls
$('#lefty').click(function(){
    if($('.container').scrollLeft() == 0)

        {$('#lefty').hide()}
    $('#righty').show();   
 $(".container").animate({scrollLeft: "-=100px"})
 })
//right arrow controls
$('#righty').click(function(){
    if ($('.container')[0].scrollWidth - $('.container').scrollLeft() == $('.container').width())
      {$("#righty").hide()}
    $('#lefty').show(); 
 $(".container").animate({scrollLeft: "+=100px"})
 })

2 个答案:

答案 0 :(得分:0)

您需要在动画完成后应用条件,在当前代码中,在动画期间使用某个值评估条件。使用此:

//Hide left at start
$('#lefty').hide();

//left arrow controls
$('#lefty').click(function(){

    $('#righty').show();   
    $(".container").animate({scrollLeft: "-=100px"}, "normal", function(){
        if($('.container').scrollLeft() <= 0){
            $('#lefty').hide();
        }
    });
});

//right arrow controls
$('#righty').click(function(){
    $('#lefty').show(); 

    $(".container").animate({scrollLeft: "+=100px"}, "normal", function(){
        if ($('.container')[0].scrollWidth - $('.container').scrollLeft() == $('.container').width()){
            $("#righty").hide();
        }
    });
});

答案 1 :(得分:0)

我不确定这是否是最好的方式,但有效。我只是添加一个div来打印宽度,只需更改验证。查看jsfiddle以查看其工作原理。

js fiddle

//Hide left at start
$('#lefty').hide();
//left arrow controls
$('#lefty').click(function(){
    $("#mensaje").append("<br>"+$('.container').scrollLeft());
if($('.container').scrollLeft() <= 100 )
    {$('#lefty').hide()}
$('#righty').show();   
$(".container").animate({scrollLeft: "-=100px"})
})
//right arrow controls
$('#righty').click(function(){
        $("mensaje").append("<br>");
        $("#mensaje").append($('.container')[0].scrollWidth -     $('.container').scrollLeft());
if ($('.container')[0].scrollWidth - $('.container').scrollLeft() <= 500)
  {$("#righty").hide()}
$('#lefty').show(); 
$(".container").animate({scrollLeft: "+=100px"})
})
相关问题