So DOM scrollIntoView aligns top/bottom, but what about left/right?

后端 未结 2 583
无人共我
无人共我 2021-01-07 22:21

I would like to scroll horizontally the given element. The only way I find is using ScrollIntoView DOM method, which allows either align the element\'s bottom with the view

2条回答
  •  囚心锁ツ
    2021-01-07 22:50

    This is something I used a while back. There might be better and more efficient way of doing it but this gets the work done:

    $(".item").click(function(event){
        event.preventDefault();
        // I broke it down into variable to make it easier to read
        var tgt_full = this.href,
            parts = tgt_full.split("#"),
            tgt_clean = parts[1],
            tgt_offset = $("#"+tgt_clean).offset(),
            tgt_left = tgt_offset.left;
    
        $('html, body').animate({scrollLeft:tgt_left}, 1000, "easeInOutExpo");          
    })
    

    You just need to make sure that the item is an a tag with an href that corresponds to the target id element:

    HTML:

    go to section 1
    ...
    
    Section 1

    Hope this helps!

提交回复
热议问题