JavaScript Tutorial/jQuery/offset

Материал из Web эксперт
Перейти к: навигация, поиск

Get offset

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var b = $("b:last");
            var offset = b.offset();
            alert(offset.left);
            alert(offset.top);
        });
    </script>
  </head>
  <body>
    <body>
      
       <b>Hello asdf asdf</b>
    </body>
</html>


Get top

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var b = $("b:last");
            var offset = b.offset();
            alert(offset.left);
            alert(offset.top);
        });
    </script>
  </head>
  <body>
    <body>
      
       <b>Hello asdf asdf</b>
    </body>
</html>


offset(): returned object contains two Integer properties, top and left. (works only with visible elements)

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
        
            var p = $("p:last");
            var offset = p.offset();
            p.html( "left: " + offset.left + ", top: " + offset.top );
            
        });
    </script>
  </head>
  <body>
    <body>
         <p>Hello</p><p>2nd Paragraph</p>
                 
    </body>
</html>


Output tag and coordinates

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("*", document.body).click(function (e) {
                  var offset = $(this).offset();
                  e.stopPropagation();
                  alert(this.tagName + " coords ( " + offset.left + ", " +
                                                  offset.top + " )");
           });

        });
    </script>
  </head>
  <body>
    <body>
      
       <b>Hello asdf asdf</b>
    </body>
</html>