Pregunta

Tengo una lista de pulgares en un DIV desplazable, animado con el botón Siguiente/Previo. Cada clic en el botón "Siguiente" debe coincidir con el atributo del primer elemento visible. Cada clic en el botón "anterior" debería darme el atributo del último elemento visible.

Realmente no sé cómo resolver eso matemáticamente, porque la distancia de desplazamiento es variable cuando la lista finaliza. ¿Puede alguien ayudarme?

Html

$<div id="scrollContent">
    <ul id="assetList">
        <li data-asset-id="15201"></li>
        <li data-asset-id="15202"></li>
        <li data-asset-id="15203"></li>
        ...        
    </ul>
</div>
<a class="next" href="#">next</a>
<a class="prev" href="#">prev</a>

jQuery

$('a.next').click(function() {
    var scrollheight = $("#scrollContent").scrollTop();
    $("#scrollContent").animate({scrollTop:scrollheight+375},500,function() {  
        // get "data-asset-id" of first visible element in viewport

    });
});

$('a.prev').click(function() {
    var scrollheight = $("#scrollContent").scrollTop();
    $("#scrollContent").animate({scrollTop:scrollheight-375},500,function() {
        // get "data-asset-id" of last visible element in viewport

    });
});

Mira el violín:http://jsfiddle.net/descodlov/77xjd/10/

Gracias.

¿Fue útil?

Solución

¿Es esto lo que estás buscando? :

var first, last;

$('a.next').click(function() {
    var scrollheight = $("#scrollContent").scrollTop();
    $("#scrollContent").animate({scrollTop:scrollheight+375},500,function() {  
        $("#assetList li").each(function() {
            if ($(this).offset().top == 1 && $(this).offset().left == 0) {
                first = $(this).attr('data-asset-id');
            }
        });
    });
});

$('a.prev').click(function() {
    var scrollheight = $("#scrollContent").scrollTop();
    $("#scrollContent").animate({scrollTop:scrollheight-375},500,function() {
        var Otop = $("#scrollContent").height() - $("#assetList li").height() - parseInt($("#assetList li").css('margin-top'));
        var Oleft = ($("#assetList li").width() + parseInt($("#assetList li").css('margin-right'))) * 3;
        $("#assetList li").each(function() {
            if ($(this).offset().top == Otop && $(this).offset().left == Oleft) {
                last = $(this).attr('data-asset-id');
            }
        });
    });
});

Violín : http://jsfiddle.net/77xjd/17/

Otros consejos

Por visibilidad, supongo que el elemento debería al menos tener la esquina superior visible. Si solo desea seleccionar elementos que sean completamente visibles, agregue o reduzca el width() y height() valores del elemento. El código básico se muestra a continuación:

var $first, $last,
    $container = $("#assetList"),
    $items = $container.children("li"),
    positions = container.offset(),
    rightside = positions.left + $container.width(),
    bottomside = positions.top + $container.height();
$items.each(function(){
    var $this = $(this),
        position = $this.offset();
               // If <li> top post >= <ul> top
    if ($first && position.top >= positions.top
               // If <li> left >= <ul> left
               && positions.left >= position.left) {
             /* Optionally, add two more conditions, to only accept elememts
                which are fully visible: 
               && positions.top + $this.height() <= bottomside
               && positions.left + $this.width() <= leftside
              */
        $first = this;
    }
    // See previous comments.
    if (position.top < bottomside && position.left < rightside) {
        $last = this;
    }
});
// $first = first visible element, eg [HTMLLiElement]
// $last = last visible element, eg [HTMLLiElement]

Acabo de actualizar la solución en tu violín.

Cacé en caché las posiciones superiores de Li de Li en el momento de inicialización y las usé para averiguar qué elemento está obteniendo la posición, cuando hace clic en el botón siguiente o anterior.

y por supuesto he copiado las líneas a continuación de Rob W's responder.

var $container = $("#assetList"),
$items = $container.children("li"),
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top