Javascript scrollIntoView() middle alignment?

后端 未结 10 1398
刺人心
刺人心 2020-12-13 03:41

Javascript .scrollIntoView(boolean) provide only two alignment option.

  1. top
  2. bottom

What if I want to scroll the view such t

10条回答
  •  盖世英雄少女心
    2020-12-13 03:53

    Improving the answer of @Rohan Orton to work for vertical and horizontal scroll.

    The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

    var ele = $x("//a[.='Ask Question']");
    console.log( ele );
    
    scrollIntoView( ele[0] );
    
    function scrollIntoView( element ) {
        var innerHeight_Half = (window.innerHeight >> 1); // Int value
                            // = (window.innerHeight / 2); // Float value
        console.log('innerHeight_Half : '+ innerHeight_Half);
    
        var elementRect = element.getBoundingClientRect();
    
        window.scrollBy( (elementRect.left >> 1), elementRect.top - innerHeight_Half);
    }
    

    Using Bitwise operator right shift to get int value after dividing.

    console.log( 25 / 2 ); // 12.5
    console.log( 25 >> 1 ); // 12
    

提交回复
热议问题