jQuery get the location of an element relative to window

后端 未结 7 1569
小鲜肉
小鲜肉 2020-11-28 01:20

Given an HTML DOM ID, how to get an element\'s position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent sinc

7条回答
  •  情话喂你
    2020-11-28 01:50

    Initially, Grab the .offset position of the element and calculate its relative position with respect to window

    Refer :
    1. offset
    2. scroll
    3. scrollTop

    You can give it a try at this fiddle

    Following few lines of code explains how this can be solved

    when .scroll event is performed, we calculate the relative position of the element with respect to window object

    $(window).scroll(function () {
        console.log(eTop - $(window).scrollTop());
    });
    

    when scroll is performed in browser, we call the above event handler function

    code snippet


    function log(txt) {
      $("#log").html("location : " + txt + " px")
    }
    
    $(function() {
      var eTop = $('#element').offset().top; //get the offset top of the element
      log(eTop - $(window).scrollTop()); //position of the ele w.r.t window
    
      $(window).scroll(function() { //when window is scrolled
        log(eTop - $(window).scrollTop());
      });
    });
    #element {
      margin: 140px;
      text-align: center;
      padding: 5px;
      width: 200px;
      height: 200px;
      border: 1px solid #0099f9;
      border-radius: 3px;
      background: #444;
      color: #0099d9;
      opacity: 0.6;
    }
    #log {
      position: fixed;
      top: 40px;
      left: 40px;
      color: #333;
    }
    #scroll {
      position: fixed;
      bottom: 10px;
      right: 10px;
      border: 1px solid #000;
      border-radius: 2px;
      padding: 5px;
    }
    
    
    Hello
    World
    Scroll Down

提交回复
热议问题