Advanced Chapter of JavaScript

Keywords: Javascript Attribute Windows less

How to insert JS
JS Basic Grammar
Grammar, function, method
Extract the string substring()
The substring() method is used to extract characters between two specified subscripts in a string.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>string object</title>
<script type="text/javascript">
var mystr="Hello World!"
document.write(  mystr.substring(6)       + "<br />");
document.write(  mystr.substring(0,5)              );
</script>
</head>
<body>
</body>
</html>
image.png

Use substring() to extract strings from strings, code as follows:

<script type="text/javascript">
  var mystr="I love JavaScript";
  document.write(mystr.substring(7));
  document.write(mystr.substring(2,6));
</script>

Operation results:

JavaScript
love

Extract a specified number of characters substr()

The substr() method extracts from the string a specified number of strings starting at the startPos t position.

Use substr() to extract some characters from the string. The code is as follows:

<script type="text/javascript">
  var mystr="I love JavaScript!";
  document.write(mystr.substr(7));
  document.write(mystr.substr(2,4));
</script>

Operation results:

JavaScript!
love

Math object
Math object, which provides mathematical calculation of data.

Using the attributes and methods of Math, the code is as follows:

<script type="text/javascript">
  var mypi=Math.PI; 
  var myabs=Math.abs(-15);
  document.write(mypi);
  document.write(myabs);
</script>

Operation results:

3.141592653589793
15

abs(x)
Absolute value of return number

Math Object Method

image

Take up the whole ceil()
The ceil() method integrates a number up.

Grammar:

Math.ceil(x)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
  document.write(Math.ceil(3.3) + "<br />")
  document.write(Math.ceil(-0.1) + "<br />")
  document.write(Math.ceil(-9.9) + "<br />")
  document.write(Math.ceil(8.9) + "<br />")
</script>
</head>
<body>
</body>
</html>
image.png
<script type="text/javascript">
  document.write(Math.ceil(0.8) + "<br />")
  document.write(Math.ceil(6.3) + "<br />")
  document.write(Math.ceil(5) + "<br />")
  document.write(Math.ceil(3.5) + "<br />")
  document.write(Math.ceil(-5.1) + "<br />")
  document.write(Math.ceil(-5.9))
</script>

Operation results:

1
7
5
4
-5
-5

Take down the whole floor()
floor() method integrates a number downward.

<script type="text/javascript">
  document.write(Math.floor(0.8)+ "<br>")
  document.write(Math.floor(6.3)+ "<br>")
  document.write(Math.floor(5)+ "<br>")
  document.write(Math.floor(3.5)+ "<br>")
  document.write(Math.floor(-5.1)+ "<br>")
  document.write(Math.floor(-5.9))
</script>
//Operation results:

0
6
5
3
-6
-6
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
document.write(Math.floor(3.3)+ "<br>")
document.write(Math.floor(-0.1)+ "<br>")
document.write(Math.floor(-9.9)+ "<br>")
document.write(Math.floor(8.9)+ "<br>")
</script>
</head>
<body>
</body>
</html>

Round round()
The round() method rounds a number to the nearest integer.

Grammar:

Math.round(x)
<script type="text/javascript">
  document.write(Math.round(1.6)+ "<br>");
  document.write(Math.round(2.5)+ "<br>");
  document.write(Math.round(0.49)+ "<br>");
  document.write(Math.round(-6.4)+ "<br>");
  document.write(Math.round(-6.6));
</script>

Operation results:

2
3
0
-6
-7

random()
The random() method returns a random number between 0 and 1 (greater than or equal to 0 but less than 1).

Grammar:

Math.random();

Returns a positive numeric value for a symbol greater than or equal to 0 but less than 1.

Get a random number between 0 and 1. The code is as follows:

<script type="text/javascript">
  document.write(Math.random());
</script>

Operation results:

0.190305486195328  

Obtain the random number between 0 and 10. The code is as follows:

<script type="text/javascript">
  document.write((Math.random())*10);
</script>

Operation results:

8.72153625893887
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Math </title>
<script type="text/javascript">
document.write(Math.round((Math.random())*10));
</script>
</head>
<body>
</body>
</html>

Array array object
Array method
concat()
Connect two or more arrays and return results

join()
Put all elements of an array into a string

pop()
Delete and return the last element of the array

push()
Add one or more elements to the end of the array and return a new length

reverse()
Reverse the order of elements in an array

shift()
Delete and return the first element of the array

slice()
Returns the selected element from an existing array

sort()
Sort the elements of an array

splice()
Delete elements and add new elements to arrays

toSource()
Returns the source code for the object

toString()
Converts an array to a string and returns the result

toLocaleString()
Converts an array to a local array and returns the result

unshift()
Add one or more elements to the beginning of the array and return a new length

valueOf()
Returns the original value of an array object

Array connection concat()
The concat() method is used to connect two or more arrays. This method returns a new array without changing the original array.

<script type="text/javascript">
  var mya = new Array(3);
  mya[0] = "1";
  mya[1] = "2";
  mya[2] = "3";
  document.write(mya.concat(4,5)+"<br>");
  document.write(mya); 
</script>

Operation results:

1,2,3,4,5
1,2,3
<script type="text/javascript">
  var mya1= new Array("hello!")
  var mya2= new Array("I","love");
  var mya3= new Array("JavaScript","!");
  var mya4=mya1.concat(mya2,mya3);
  document.write(mya4);
</script>

Operation results:

hello!,I,love,JavaScript,!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array object </title>
<script type="text/javascript">
    var myarr1= new Array("010")
    var myarr2= new Array("-","123456789");
    document.write(myarr1.concat(myarr2))
</script>
</head>
<body>
</body>
</html>

Specifies a delimiter to join the array element join()
The join() method is used to put all elements in an array into a string. Elements are delimited by a specified delimiter.

Grammar:

ArrayObject. join (separator)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array object </title>
<script type="text/javascript">
    var myarr1= new Array("86","010")
    var myarr2= new Array("123456789");
   var myarr3= myarr1.concat(myarr2);
document.write(myarr3.join("-"));
</script>
</head>
<body>
</body>
</html>

Reverse array element order ()
The reverse() method is used to reverse the order of elements in an array.

Define the array myarr and assign values, then reverse the order of its elements:

<script type="text/javascript">
  var myarr = new Array(3)
  myarr[0] = "1"
  myarr[1] = "2"
  myarr[2] = "3"
  document.write(myarr + "<br />")
  document.write(myarr.reverse())
</script>

Operation results:

1,2,3
3,2,1

Selected element slice()
The slice() method returns the selected element from an existing array.

grammar

arrayObject.slice(start,end)

Negative values can be used to select elements from the end of the array.

String.slice() is similar to Array.slice().

<script type="text/javascript">
  var myarr = new Array(1,2,3,4,5,6);
  document.write(myarr + "<br>");
  document.write(myarr.slice(2,4) + "<br>");
  document.write(myarr);
</script>

Operation results:

1,2,3,4,5,6
3,4
1,2,3,4,5,6
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array object </title>
<script type="text/javascript">
   var myarr1= ["I","love","you"];
   document.write(myarr1.slice(1,3))
</script>
</head>
<body>
</body>
</html>
image.png

Array sort()
The sort() method arranges elements in an array in a certain order.

Grammar:

ArrayObject. sort (method function)
<script type="text/javascript">
  function sortNum(a,b) {
  return a - b;
 //In ascending order, such as descending order, the word "a - b" should be "b - a"
}
 var myarr = new Array("80","16","50","6","100","1");
  document.write(myarr + "<br>");
  document.write(myarr.sort(sortNum));
</script>

Operation results:

80,16,50,6,100,1
1,6,16,50,80,100

The parseInt() string type is converted to an integer.

<!DOCTYPE  HTML>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fasten Safety Belt,Ready to sail</title>

<script type="text/javascript">

  //Get the current date through the date object of javascript and output it.
    var T=new Date();
    var weekday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
    var myw=T.getDay();
    document.write("Today's date is:"+T+weekday[myw]+"<br>");
    
  //Achievement is a long string is not easy to handle, after finding the rules of segmentation into the array is better to operate oh
  var scoreStr = "Xiao Ming:87;Floret:81;Xiaohong:97;Small day:76;Xiao Zhang:74;Little:94;Xiaoxi:90;Xiao Wu:76;Xiao di:64;Xiaoman:76";
  var myarr=[10];
  myarr=scoreStr.split(";");
  for(i=0;i<10;i++){
      document.write(myarr[i]+"<br>");
  }
  //Find out the results from the array, then sum them up and output them.
  var sum=0;
  for(i=0;i<10;i++){
      sum=sum+parseInt(myarr[i].substr(3));
      document.write(sum+"<br>");
  }
    

</script>
</head>
<body>
</body>
</html>

Windows object
Windows object is the core of BOM. Windows object refers to the current browser window.

alert()
Displays a warning box with a message and a confirmation button

prompt()
Displays a dialog box that prompts the user for input

confirm()
Displays a dialog box with a message and confirmation and cancellation buttons

open()
Open a new flow window or find a named window

close()
Close the browser window

print()
Print the contents of the current window

focus()
Give keyboard focus to a window

blur()
Remove keyboard focus from the top window

One-time timer: Triggers only once after a specified delay time.
Interval trigger timer: Triggered every certain time interval.

setTimeout()
Execute the code after the specified delay time

clearTimeout()
Cancel setTimeout() settings

setInterval()
Execute code at specified intervals

clearInterval()
Cancel setInterval() settings

Timer setTimeout()
setTimeout() timer, which delays the specified time after loading, executes the expression once, only once.
Grammar:
SetTimeout (code, delay time);

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>timer</title>
<script type="text/javascript">
  var num=0;
  function startCount() {
    document.getElementById('count').value=num;
    num=num+1;
    setTimeout("startCount()",100);
  }
    setTimeout("startCount()",100);
</script>
</head>
<body>
<form>
<input type="text" id="count" />
</form>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>timer</title>

<script type="text/javascript">
  var num=0;
  var i;
  function startCount(){
    document.getElementById('count').value=num;
    num=num+1;
    i=setTimeout("startCount()",1000);
  }
  function stopCount(){
     clearTimeout(i);
  }
</script>
</head>
<body>
  <form>
    <input type="text" id="count" />
    <input type="button" value="Start"  onclick="startCount()" />
    <input type="button" value="Stop"   onclick="stopCount()" />
  </form>
</body>
</html>

History object
history objects record the pages (URLs) that users have visited, and can realize the similar navigation function of browser forward and backward.

History object properties
length returns the number of URLs in the browser history list

History object method

back() loads the first url in the history list

forward() loads the next url in the history list

go() loads a specific page in the history list

<script type="text/javascript">
  var HL = window.history.length;
  document.write(HL);
</script>

Return to the previous page you browsed
The back() method loads the first URL in the history list.

Grammar:

window.history.back();

back() is equivalent to go(-1), and the code is as follows:

window.history.go(-1);

Return to the next page to browse

window.history.forward();

window.history.go(1);

Location object
location is used to get or set the form's URL, and it can be used to parse the URL.

location object property:
hash
Set or return the url starting with the well number
host
Set or return the host name and port number of the current url
hostname
Set or return the host name of the current url

href
Setting or returning a complete url
pathname
Set or return the path portion of the current url

port
Set or return the port number of the current url
protocol
Setting or returning the protocol for the current url

location object method:
assign()
Loading new documents
reload()
Reload the current document
replace()
Replace the current document with a new document

Navigator object
Navigator objects contain information about browsers and are often used to detect versions of browsers and operating systems.

Object properties:

appCodeName
String Representation of Browser Code Name

appName
Returns the name of the browser

appVersion
Return browser platform and version information

platform
Return to the operating system platform running the browser

userAgent
Returns the value of the user-agent header of the sending server by the client

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>navigator</title>
<script type="text/javascript">
  function validB(){ 
    var u_agent = navigator.userAgent ; 
    var B_name="Not the mainstream browser you want to use!"; 
    if(u_agent.indexOf("Firefox")>-1){ 
        B_name="Firefox"; 
    }else if(u_agent.indexOf("Chrome")>-1){ 
        B_name="Chrome"; 
    }else if(u_agent.indexOf("MSIE")>-1&&u_agent.indexOf("Trident")>-1){ 
        B_name="IE(8-10)";  
    }
        document.write("Browser:"+B_name+"<br><br>");
        document.write("u_agent:"+u_agent+"<br>"); 
  } 
</script>
</head>
<body>
  <form>
     <input type="button" value="View Browser"  onclick="validB()" >
  </form>
</body>
</html>

screen object
The screen object is used to get the user's screen information.

Grammar:

window.screen. Properties

availHeight
Screen height available for windows
availWidth
Screen width available for windows

colorDepth
Number of color bits represented by user browsers
pixelDepth
Number of color bits represented by user browsers
height
Screen Height
width
Width of screen

High and Width of Screen Resolution
The window.screen object contains information about the user screen.

  1. screen.height returns high screen resolution
  2. screen.width returns the width of the screen resolution
<script type="text/javascript">
  document.write( "Screen width:"+screen.width+"px<br />" );
  document.write( "Screen Height:"+screen.height+"px<br />" );
</script>

Screen Available Height and Width

  1. The screen.availWidth attribute returns the width of the visitor's screen, minus the interface features, such as the taskbar, in pixels.

  2. The screen.availHeight attribute returns the height of the visitor's screen, subtracting the interface features, such as the taskbar, in pixels.

<!DOCTYPE html>
<html>
 <head>
  <title>Browser Object</title>  
  <meta http-equiv="Content-Type" content="text/html; charset=gkb"/>   
 </head>
 <body>
  <!--Write web page layout first-->
  <h3>Successful operation</h3>
  <span id="second">5</span>
  <span>Back to home page in seconds</span>
  <a href="javascript:back()">Return</a>
  <script type="text/javascript">  
    var num = document.getElementById("second").innerHTML;
   //Gets the element that displays the number of seconds, and changes the number of seconds through a timer.
    function count(){
        num--;
        document.getElementById("second").innerHTML=num;
        if(num==1){
            window.location.assign("https://www.123.com");
        }
        
    }
    setInterval("count()",1000);
   //The location and history objects of window s are used to control the jump of web pages.
   function back(){
       window.history.back();
   }
 </script> 
</body>
</html>

Node properties:
nodeName:
Returns a string containing the name of a given node

nodeType:
Returns an integer representing the type of a given node

nodeValue:
The current value returned to the node

Traversing the node tree:
childNodes
Returns an array

firstChild
Returns the first child node

lastChild
Returns the last node

parentNode
Returns the parent of a given node

nextSibling
Returns the next child of a given node

previousSibling
Returns the last child of a given node

createElement(element)
Create a new element node

createTextNode()
Create a new text node containing the given text

appendChild()
Add a new child node after the last child node list of the specified node

insertBefore()
Insert a given node in front of a given subnode of a given element node

removeChild()
Delete a child node from a given element

replaceChild()
Replace one child node in a given parent element with another

getElementsByName() method
Returns a collection of node objects with a specified name.

getElementsByTagName() method
Returns a collection of node objects with the specified tag name.

Distinguish getElementByID,getElementsByName,getElementsByTagName


image.png
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
        <title>Untitled document</title>
    </head>    
    <body>
        <form>
          //Please choose your hobby: <br>
          <input type="checkbox" name="hobby" id="hobby1">  Music
          <input type="checkbox" name="hobby" id="hobby2">  Mountaineering
          <input type="checkbox" name="hobby" id="hobby3">  Swimming
          <input type="checkbox" name="hobby" id="hobby4">  Read
          <input type="checkbox" name="hobby" id="hobby5">  Play a ball
          <input type="checkbox" name="hobby" id="hobby6">  Run <br>
          <input type="button" value = "All election" onclick = "checkall();">
          <input type="button" value = "Not at all" onclick = "clearall();">
          <p>Please enter the serial number of your hobby, which is 1.-6:</p>
          <input id="wb" name="wb" type="text" >
          <input name="ok" type="button" value="Determine" onclick = "checkone();">
        </form>
        <script type="text/javascript">
        function checkall(){
            var hobby = document.getElementsByTagName("input");
            for(i = 0;i < hobby.length;i++){
                    if(hobby[i].type == "checkbox"){
                      hobby[i].checked = true;   }
                  }
        }
        function clearall(){
            var hobby = document.getElementsByName("hobby");
            for(i = 0;i < hobby.length;i++){
                hobby[i].checked = false;}
        }        
        function checkone(){
            var j=document.getElementById("wb").value;
            var hobby = document.getElementById("hobby"+j);
            hobby.checked = true;    }        
        </script>
    </body>
</html>

getAttribute() method
Get the value of the attribute by the attribute name of the element node.

Using getElementById(), getElementsByTagName(), the element nodes are obtained.

getElementsByTagName(); gets a collection

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>getAttribute()</title>
</head>
<body>   
<p id="intro">Course List</p>  
    <ul>  
        <li title="First li">HTML</li>  
        <li>CSS</li>  
        <li title="Third li">JavaScript</li>  
        <li title="Fourth li">Jquery</li>  
        <li>Html5</li>  
    </ul>  
<p>The following is not empty for acquisition li Label title value:</p>
<script type="text/javascript">
    var con=document.getElementsByTagName("li");
    for (var i=0; i< con.length;i++){
    var text=con[i].getAttribute("title");
      if(text!=null)
      {
        document.write(text+"<br>");
      }
    } 
 </script> 
</body>
</html>

setAttribute() method
The setAttribute() method adds a new property with the specified name and value, or sets an existing property to the specified value.

In Document Object Model (DOM), each node is an object.

nodeName: The name of the node
nodeValue: The value of the node
nodeType: Type of node

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Node attributes</title>
</head>
<body>
  <ul>
     <li>javascript</li>
     <li>HTML/CSS</li>
     <li>jQuery</li>     
  </ul>
  <script type="text/javascript">
    var con=document.getElementsByTagName("li");
    for(i=0;i<con.length;i++){
        document.write(con[i].nodeName+"<br>");
        document.write(con[i].nodeValue+"<br>");
        document.write(con[i].nodeType+"<br>");
    }
  </script>
</body>
</html>

Accessing child Nodes

First and last entries to access subnodes
node.firstChild
node.lastChild

Accessing parent node parentNode
Gets the parent of the specified node

Accessing Brother Nodes
nodeObject.nextSibling

The previousSibling attribute returns the node immediately preceding a node

Insert node appendChild()
Add a new child node after the last child node list of the specified node.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled document</title>
</head>
<body>

<ul id="test">
  <li>JavaScript</li>
  <li>HTML</li>
</ul> 
 
<script type="text/javascript">

  var otest = document.getElementById("test");  
  var newnode = document.createElement("li");
  var newtext= document.createTextNode("PHP"); 
  newnode.appendChild(newtext); 
  otest.appendChild(newnode);
          
</script> 

</body>
</html>

Insert node insertBefore()
insertBefore() method can insert a new subnode before the existing subnode.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled document</title>
</head>
<body>

<ul id="test"><li>JavaScript</li><li>HTML</li></ul> 

<script type="text/javascript">

  var otest = document.getElementById("test");  
  var newnode = document.createElement("li");
  newnode.innerHTML = "PHP" ;  
 otest.insertBefore(newnode,otest.childNodes[1]); 
          
</script> 

</body>
</html>

Delete the node removeChild()
removeChild() method deletes a node from the list of child nodes. If the deletion is successful, this method can return the deleted node, or NULL if it fails.

function clearText() {
  var content=document.getElementById("content");
  for(var i=content.childNodes.length-1;i>=0;i--){
     var childNode = content.childNodes[i];
     content.removeChild(childNode);
  }
}

Replace element node replaceChild()
ReplceChild implements substitution of child nodes (objects). Returns a reference to the replaced object.

function replaceMessage(){
           var oldnode=document.getElementById("oldnode");
           var oldHTML= oldnode.innerHTML;           
           var newnode=document.createElement("i");         
           oldnode.parentNode.replaceChild(newnode,oldnode);
           newnode.innerHTML=oldHTML;
           
}  

Create element node createElement
The createElement() method creates element nodes. This method returns an Element object.

Create the text node createTextNode
The createTextNode() method creates a new text node and returns the newly created Text node.

<script type="text/javascript">

   var element = document.createElement("p");
   element.className = "message";
   var textNode = document.createTextNode("I love JavaScript!");
   element.appendChild(textNode);
   document.body.appendChild(element);
        
</script> 

Visual area size of browser window
window.innerHeight - Internal height of browser window

window.innerWidth - Internal Width of Browser Window

For Internet Explorer 8, 7, 6, 5:

document.documentElement.clientHeight denotes the current height of the window in which the HTML document resides.

document.documentElement.clientWidth denotes the current width of the window in which the HTML document resides.

The body attribute of the Document object corresponds to the < body > tag of the HTML document

• document.body.clientHeight

• document.body.clientWidth

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<script type="text/javascript">
    var w=document.documentElement.clientWidth;
    var h=document.documentElement.clientHeight;
    document.write(w,"<br>",h);
</script>
</body>
</html>

Web page size scroll Height
Scroll Height and scroll Width to get the height and width of the content.
ScollHeight is the actual height of the content of a web page, which can be smaller than clientHeight.
Scroll Height is the height of the content of the page, but the minimum value is clientHeight.

    var h=document.documentElement.scrollHeight;
    var w=document.documentElement.scrollWidth;
    document.write(h,"<br>",w);

Web page size offsetHeight
OffetHeight and offsetWidth are used to get the height and width of the content (including scrollbar contours, which vary with the display size of the window).
OffsetHeight = client Height + scrollbar + border.
Browser Compatibility

var w= document.documentElement.offsetWidth

Browser Compatibility

var w= document.documentElement.offsetWidth
|| document.body.offsetWidth;
var h= document.documentElement.offsetHeight
|| document.body.offsetHeight;

<!DOCTYPE HTML>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head>
<body>
 <script type="text/javascript">
var w= document.documentElement.offsetWidth
    || document.body.offsetWidth;
var h= document.documentElement.offsetHeight
    || document.body.offsetHeight;
document.write(w+"<br>");
document.write(h);
</script>
</body>
</html>

Distance and offset of web page scrolling
scrollLeft: Sets or gets the distance between the left edge of a given object and the leftmost end of the currently visible content in the window, that is, the gray content on the left.

scrollTop: Sets or gets the distance between the top of the object and the top of the visible content in the window, that is, the gray content above.

offsetLeft: Gets the calculated left-hand position of the specified object relative to the layout or parent coordinates specified by the offsetParent attribute.

offsetTop: Gets the calculated top position of the specified object relative to the layout or parent coordinates specified by the offsetParent attribute.

<!DOCTYPE HTML>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
    function req(){
          var div = document.getElementById("div1");
          document.getElementById("li1").innerHTML = (div.offsetTop)+"px";//Distance of div1 from the top of the screen
          document.getElementById("li2").innerHTML = (div.offsetLeft)+"px";//Distance from div1 to the left of the screen
          document.getElementById("li3").innerHTML = (div.scrollTop)+"px";//Distance of Divid1 Longitudinal Scroll Bar Rolling
          document.getElementById("li4").innerHTML = (div.scrollLeft)+"px";//Distance of div1 horizontal scrollbar rolling
     }
</script>
</head>
<body style="border:10px solid #ccc;padding:0px 0px;margin:5px 10px">
    <div style="width:60%;border-right:1px dashed red;float:left;">
        <div style="float:left;">
            <div id="div1" style="border:5px red solid;height:300px;width:200px;overflow:auto">
                <div style="height:500px;width:400px">Please adjust the horizontal scroll bar and click the button to view it. offsetTop,offsetLeft,scrollTop,scrollLeft Value.</div>
            </div>
            <input type="button" value="Click on me!" onclick="req()" style="border: 1px solid purple;height: 25px;"/>
        </div>
        
    </div>
    <div style="width:30%;float:left;">
        <ul style="list-style-type: none; line-height:30px;">Result:
            <li>offsetTop : <span id="li1"></span></li>
            <li>offsetLeft : <span id="li2"></span></li>
            <li> scrollTop : <span id="li3"></span></li>
            <li>scrollLeft : <span id="li4"></span></li>
        </ul>
        
    </div>
    <div style="clear:both;"></div>    
</body>
</html>
image.png
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Practical problems - tab</title>
    <style type="text/css">
     /* CSS Style Making */  
     *{margin:0;padding:0;font:normal 12px "Microsoft YaHei";color:#000000;}
     ul{list-style-type: none;}
     a{text-decoration: none;}

     #tab-list{width: 275px;height:190px;margin: 20px auto;}

     #ul1{border-bottom: 2px solid #8B4513;height: 32px;}
     #ul1 li{display: inline-block;width: 60px;line-height: 30px;text-align: center;border: 1px solid #999;border-bottom: none;margin-left: 5px;}
     #ul1 li:hover{cursor: pointer;}
     #ul1 li.active{border-top:2px solid #8B4513;border-bottom:2px solid #FFFFFF;}

     #tab-list div{border: 1px solid #7396B8;border-top: none;}
     #tab-list div li{height: 30px;line-height: 30px;text-indent: 8px;}
     
     .show{display: block;}.hide{display: none;}
    </style>
    <script type="text/javascript">
         
    window.onload = function() {
        var oUl1 = document.getElementById("ul1");
        var aLi = oUl1.getElementsByTagName("li");
        var oDiv = document.getElementById("tab-list");
        var aDiv = oDiv.getElementsByTagName("div");
        for(var i = 0; i < aLi.length; i++) {
            aLi[i].index = i;
            aLi[i].onmouseover = function() {
                for(var i = 0; i < aLi.length; i++) {
                    aLi[i].className = "";
                }
                this.className = "active";
                for(var j = 0; j < aDiv.length; j++) {
                    aDiv[j].className = "hide";
                }
                aDiv[this.index].className = "show";
            }        
        }
    }
    
    
    </script>
 
</head>
<body>
<!-- HTML Page layout -->
<div id="tab-list">
    <ul id="ul1">
        <li class="active">House property</li><li>Home Furnishing</li><li>Second-hand room</li>
    </ul>
    <div>
        <ul>
            <li><a href="javascript:;">275 Wanchai Changping Neighboring Railway Co., Ltd. The total price is 200,000 yuan.</a></li>
            <li><a href="javascript:;">200 Wannei Buy Five Rings, Three Residences, 1.4 million Anjiadong Three Rings</a></li>
            <li><a href="javascript:;">Beijing zero down-payment real estate 530,000 purchase East 5 Ring 50 Ping</a></li>
            <li><a href="javascript:;">Beijing Building Directly Down 5000 Citic Palace Park Building Wang Xianfang</a></li>
        </ul>
    </div>    
    <div class="hide">
        <ul>
            <li><a href="javascript:;">40 Rent flat to rebuild the mixed nest of beautiful girls</a></li>
            <li><a href="javascript:;">Classic Fresh and Simple Euro-Aijia 90-level Old House Rejuvenates</a></li>
            <li><a href="javascript:;">New Chinese Cool Color Warmth 66 Flat Colour Lively Home</a></li>
            <li><a href="javascript:;">Ceramic tile is like choosing the flue of wife's bathroom</a></li>
        </ul>
    </div>    
    <div class="hide">
        <ul>
            <li><a href="javascript:;">Tongzhou luxury 3 dwelling 2.6 million ring 2 dwelling 250 w Throw away</a></li>
            <li><a href="javascript:;">Xi3 Ring Tongtong 2 occupies 2.9 million, 1.3 million and 2 occupies limited purchase</a></li>
            <li><a href="javascript:;">Huangchenggen Primary School District is only 2.6 million, 12.1 million, and 700,000.!</a></li>
            <li><a href="javascript:;">Exclusive villas 2.8 million Suzhou Bridge 2 dwelling discount price 2.48 million</a></li>
        </ul>
    </div>
</div>

  
</body>
</html>

Tag tab


image.png

If the content of this number is not in place (such as copyright or other issues), please contact us in time to rectify it, and it will be dealt with at the first time.

Praise me, please! Because your approval / encouragement is my greatest motivation to write!

Welcome your attention Dashu Xiaosheng A short book!

This is a quality, attitude blog

Blog

Posted by Janus13 on Mon, 29 Jul 2019 21:20:57 -0700