current position:Home>DOM based on JavaScript

DOM based on JavaScript

2022-04-29 08:08:57Chen Chen is trying

DOM

DOM,Document Object Model Document object model

JS Pass through DOM Come on HTML Document for operation . Just understand DOM Can operate at will WEB page

  • file . Documents refer to web pages , A web page is a document
  • object . Object refers to converting every node in a web page into an object
  • Model . The model is used to represent the relationship between nodes , Easy to operate page

node (Node)

Nodes are the most basic units of a web page , Every part of a web page can be called a node

Although they are all nodes , But the types of nodes are different

Common nodes :

  • Document nodes (Document), On behalf of the whole page
  • Element nodes (Element), Represents the tag in the web page
  • Attribute node (Attribute), Represents the attribute of an element
  • Text node (Text), Represents the text content in the web page

DOM operation

In web pages, browsers have provided us with document object , It represents the whole web page , It is window Object properties , You can use it directly on the page .

document Query methods :

  • According to the id Property to query an element node object :document.getElementById(“id Property value ”);
  • According to the name Attribute values query a set of element node objects :document.getElementsByName(“name Property value ”);
  • Query a set of element node objects according to the tag name :document.getElementsByTagName(“ Tag name ”);
<button id="btn"> I'm a button </button>
<script type="text/javascript">
	/*console.log(document);*/
	var btn = document.getElementById("btn");
	console.log(btn.innerHTML);//" I'm a button "
	btn.innerHTML=" Hello ";
	console.log(btn.innerHTML);//" Hello "
	console.log(btn);//"[object HTMLButtonElement]"
</script>

event (Event)

Events refer to the interaction between users and browsers . such as : Click button 、 close window 、 Mouse movement ...

How to bind Events :

  1. You can set the corresponding... In the event property of the tag JS Code . Structural and behavioral coupling , Not recommended

    <button id="btn" onmousemove="alert(' hate , What do you want me to do !');"> I'm a button </button>
    
  2. You can handle events by setting callback functions for the specified event properties of an object .

    <script>
    	var btn = document.getElementById("btn");
    	// Click the response function 
    	btn.onclick = function() {
          
    		alert(" What do you want me to do !");
    	};
    </script>
    

Loading of documents

When a browser loads a page , It's loaded in top-down order , Load one line, execute one line .

If you will js Code to the top of the page , When the code is executed , On the page DOM Object is not loaded yet , You will not be able to get DOM object , Lead to DOM operation failed .

Solution one : Can be js Code to body Below

<body>
	<button id="btn"> Button </button>

	<script>
		var btn = document.getElementById("btn");
		btn.onclick = function() {
    
			alert(" ha-ha ");
		};
	</script>
</body>

Solution two : take js Code to window.onload = function(){} in

window.onload The corresponding callback function will be executed after the whole page is loaded , So you can make sure that when the code is executed , be-all DOM The object has been loaded

<script>  
    window.onload = function(){
      
        var btn = document.getElementById("btn");  
        btn.onclick = function(){
      
        };
    };
</script>

DOM Inquire about

Get element node ( adopt document Object call ):

  • getElementById() adopt id Property acquisition One Element node object
  • getElementByTagName() adopt Tag name obtain A group of Element node object
  • getElementByName() adopt name Property acquisition A group of Element node object

The child node includes the text in the note element , Child element self-contained label element

Get the child node of the element node ( Call through a specific element node ):

  • getElementsByTagName() Method , Returns the specified label name of the current node and the descendant node
  • Elements .childNodes Get the... Of the current element All child nodes , A blank text child node is obtained 【 stay IE8 And the following browsers , Do not treat nodes as child nodes 】
  • Elements .children Get the... Of the current element All sub elements
  • Elements .firstChild Get the... Of the current element First child node , A blank text child node is obtained
  • Elements .firstElementChild Get the... Of the current element The first sub element
  • Elements .lastChild Get the last child node of the current node

Get the parent node and the sibling node ( Call... Through specific nodes ):

  • Elements .parentNode Get the parent of the current element
  • Elements .previousSibling Get the previous sibling node of the current node , It is also possible to obtain blank text child nodes
  • previousElementSibling Get previous sibling element 【IE8 And below are not supported 】
  • Elements .nextSibling Get the next sibling node of the current node

innerHTML and innerText

These two properties are not in DOM Standard definition , But most browsers support these two properties . The two properties work similarly , You can get the content inside the tag , The difference is innerHTML Will get html label , and innerText Will automatically remove the label . If you use these two properties to set the content inside the tag , There is no difference

Attribute of element node :

  • obtain Element object . Property name
  • Set up Element object . Property name = New value

Other attributes :

  • nodeValu: Text nodes can be accessed through nodeValue Property to get and set the content of the text node
  • innerHTML: The element node uses this attribute to get and set the information inside the label html Code

document Other properties and methods of the object

  • document.body Get... On the page body Elements
  • document.documentElement Get the html Root element
  • document.all Get all the elements in the page , amount to document.getElementsByTagName("*");
  • document.getElementsByClassName() According to the class Attribute values query a set of element node objects 【 This method does not support IE8 And the following browsers 】
  • document.querySelector() according to CSS The selector goes to the page to query an element , If there are multiple matching elements , Then it will return the first element queried
  • document.querySelectorAll() according to CSS The selector queries the page for a set of elements , All matching elements are encapsulated into an array and returned , Even if only one

DOM modify

  • document.createElement() Used to create an element node object , It requires a tag name as a parameter , The element node object... Will be created based on the tag name , And return the created object as the return value
  • document.createTextNode() You can create a text node object based on the text content
  • appendChild Add a new child node to a parent node . usage : Father .appendChild( Child node )
  • insertBefore Insert a new node in front of the old node . usage : Parent node .insertBefore( New node , Old node )
  • replaceChild Replace the old node with a new node . usage : Parent node .replaceChild( New node , Old node )
  • removeChild Delete the specified child node . usage : Parent node .removeChild( Child node ). Recommend ways : Child node .parentNode.removeChild( Child node )
  • The above methods , In fact, the corresponding elements are changed ( label ) Of innerHTML Value .
myClick("btn07",function(){
      
    // towards city Add Guangzhou  
    var city = document.getElementById("city");  
  
    /* *  Use innerHTML It can also be done DOM Operations related to the addition, deletion and modification of  *  Generally, we will use a combination of two ways  */  
    //city.innerHTML += "<li> Guangzhou </li>"; 
  
    // Create a li 
    var li = document.createElement("li");  
    // towards li Set text in  
    li.innerHTML = " Guangzhou ";  
    // take li Add to city in  
    city.appendChild(li);  
  
});  

confirm() Used to pop up a prompt box with confirm and Cancel buttons , You need a string as an argument , The string will be displayed as prompt text .

for The loop executes immediately after the page is loaded , The response function will execute when the hyperlink is clicked , When the response function executes ,for The loop has already been executed

DOM Yes CSS The operation of

Read and modify inline styles

adopt JS Modify the inline style of the element .

grammar : Elements .style. Style name = Style value

Be careful : If the style name contains -, You need to change the style name to hump naming method - Get rid of , And then - The last letter is capitalized . for example :background-color Change it to backgroundColor

adopt style The styles set by the property are all inline styles , Inline styles have a higher priority , So pass JS Modified styles are often displayed immediately .

adopt JS Get the inline style of the element

grammar : Elements .style. Style name

adopt style Property setting and reading are inline styles , Unable to read styles in style sheet

Read the current style of the element

Gets the current display style of the element

grammar : Elements .currentStyle. Style name .

It can be used to read the style that the current element is displaying . If the current element is not set to this style , Then get its default value

currentStyle Only IE Browser support , Other browsers don't support .

Available in other browsers **getComputedStyle()** This method gets the current style of the element , The method is window Methods , You can use it directly . Two parameters are required :

  • first : The element to get the style
  • the second : You can pass a pseudo element , It's usually spread null
var obj = getComputedStyle(box1,null);
alert(obj.width);

getComputedStyle() Method returns an object , Object encapsulates the style corresponding to the current element . However, this method does not support IE8 And the following browsers

Can pass object . Style name To read the style , If the obtained style is not set , You will get the real value , Not the default . such as : No settings width, It won't get auto, It's a length

adopt currentStyle and getComputedStyle() The read styles are read-only , Do not modify , If you want to modify it, you must pass style attribute

// Normal browser mode  
alert(getComputedStyle(box1,null).backgroundColor);        
//IE8 The way  
alert(box1.currentStyle.backgroundColor);                                                           

Achieve compatibility

/* *  Define a function , Gets the current style of the specified element  *  Parameters : * obj  The element to get the style  * name  The name of the style to get  */  
function getStyle(obj , name){
      
// object . Property does not exist , No mistake. , If you look for an object directly ,( Current scope to global scope ) I can't find a mistake  
    if(window.getComputedStyle){
      
        // Normal browser mode , have getComputedStyle() Method 【IE8 And below there is no 】
        return getComputedStyle(obj , null)[name];  
    }else{
      
        //IE8 The way , No, getComputedStyle() Method  
        return obj.currentStyle[name];  
    }  
    //return window.getComputedStyle?getComputedStyle(obj , null)[name]:obj.currentStyle[name]; 
}  

Other style related properties

Be careful : The following styles are read-only , Unspecified offsets are relative to the upper left corner of the current window

attribute / Method describe
clientHeight Returns the visible height of the element ( No px), Include the height of the content area and inner margin of the element
clientWidth Returns the visible width of the element ( No px), Include the width of the content area and inner margin of the element
offsetHeight Get the height of the entire element , Including the content area 、 padding 、 Frame
offfsetWidth obtain The width of the entire element , Including the content area 、 padding 、 Frame
offsetParent The positioning parent element of the current element , Get the nearest ancestor element with location enabled
If all ancestor elements are not enabled to locate , Then return to body
offsetLeft/offsetTop The level at which the current element is positioned relative to its parent element / Vertical offset
scrollHeight/scrollWidth Get the height of the entire scrolling area of the element / Width
scrollTop/scrollLeft Get element vertical / How far the horizontal scroll bar scrolls , Determine whether the scroll bar scrolls to the end

When satisfied scrollHeight - scrollTop == clientHeight, Indicates that the vertical scroll bar scrolls to the end

When satisfied scrollWidth - scrollLeft == clientWidth, Indicates that the horizontal scroll bar has scrolled to the end

event (Event)

Event object

When the response function of an event is triggered , Every time the browser passes an event object as an argument into the response function , All information related to the current event is encapsulated in the event object , such as : Mouse coordinates 、 Which key on the keyboard is pressed 、 The direction in which the mouse wheel rolls ...

You can define a formal parameter in the response function , To use event objects , But in IE8 The event object in the following browser has not finished the argument transfer , But as a window Object's properties are saved

Example :

// Solve the compatibility problem of event objects 
 Elements . event  = function(event){
      
    event = event || window.event;  
};  
  
 Elements . event  = function(e){
      
	e = e || event;  
	  
};  

Get the coordinates of the mouse

onmousemove This event will be triggered when the mouse moves in the element

clientX and clientY Used to obtain the coordinates of the mouse in the current visible window

div The offset , Is relative to the entire page

pageX and pageY You can get the coordinates of the mouse relative to the current page

But these two properties are IE8 China does not support it. , So if you need to be compatible IE8, Do not use

var left = event.clientX;

var top = event.clientY;

The bubble of events (Bubble)

Event bubbling refers to the upward conduction of events , When an event on a descendant element is triggered , The same event on its ancestor element will also trigger .

The bubbling of events is beneficial in most cases , If you need to cancel bubbling , You need to use the event object to cancel

The event object can be cancelBubble Set to true, You can cancel the bubbling .

for example :

 Elements . event  = function(event){
      
    event = event || window.event;  
    event.cancelBubble = true;  
};

Delegation of events

We hope , Bind events only once , Can be applied to multiple elements , Even if the element is added after

We can try to bind it to the common ancestor element of the element

Refers to the common ancestor element that uniformly binds events to elements , So when an event on a descendant element triggers , Will bubble all the way to the ancestral element . The event is handled by the response function of the ancestor element .

Event delegation takes advantage of bubbling , Delegate can reduce the number of event bindings , Improve the performance of the program .

target : event Medium target Represents the object that triggers the event

Binding of events

Use object . event = function Bind the response function in the form of , It can only bind a response function for an event of an element at the same time , You can't bind more than one , If multiple , Then the back will cover the front

addEventListener()

Through this method, you can also bind the response function for the element . Parameters :

  1. The string of the event , Don't on
  2. Callback function , This function is called when the event is triggered
  3. Whether the event is triggered during the capture phase , A Boolean value is required , It's usually spread false

Use addEventListener() Multiple response functions can be bound simultaneously for the same event of an element ,

So when the event is triggered , The response functions will be executed in the binding order of the functions

This method does not support IE8 And the following browsers

btn01.addEventListener("click",function(){
      
	alert(1);  
},false);  
  
btn01.addEventListener("click",function(){
      
	alert(2);  
},false);					  

attachEvent()

stay IE8 Can be used in attachEvent() To bind events . Parameters :

  1. The string of the event , want on
  2. Callback function

This method can also bind multiple handlers for an event at the same time , The difference is that it executes after binding , The order of execution and addEventListener() contrary

btn01.attachEvent("onclick",function(){
      
alert(1);  
});  
  
btn01.attachEvent("onclick",function(){
      
alert(2);  
});	  
// Define a function , Used to bind the response function for the specified element  
/* * addEventListener() Medium this, Is the object that binds the event  * attachEvent() Medium this, yes window *  Need to unify the two methods this */  
/* *  Parameters : * obj  Object to bind event  * eventStr  The string of the event ( Don't on) * callback  Callback function  */  
function bind(obj , eventStr , callback){
      
    if(obj.addEventListener){
      
        // Most browsers are compatible  
        obj.addEventListener(eventStr , callback , false);  
    }else{
      
        /* * this Who is determined by the calling method  * callback.call(obj) */  
        //IE8 And the following  
        obj.attachEvent("on"+eventStr , function(){
      
            // Callback function is invoked in anonymous function  
            callback.call(obj);  
        });  
    }  
}  

Dissemination of events

Netscape and Microsoft have different understandings about the spread of the incident :

  • Microsoft believes that events should spread from the inside out , That is, when an event is triggered , Events on the current element should be triggered first , And then propagate to the ancestor of the current element , In other words, the event should be executed in the bubbling phase .

  • Netscape believes that events should be spread from outside to inside , That is, when an event is triggered , The event of the outermost ancestor element of the current element should be triggered first , And then it's spreading inward to the next generation of elements

W3C A combination of the two companies , The spread of events is divided into three stages :

  1. Capture phase . In the capture phase, from the outermost ancestor element , Capture events to target elements , But by default, no event is triggered at this time 【IE8 There is no capture phase in browsers and below 】
  2. Target stage . Event capture to target element , The end of capture starts to trigger an event on the target element
  3. bubbling phase . Events pass from the target element to its ancestor element , Trigger events on ancestor elements in turn

If you want to trigger events during the capture phase , Can be addEventListener() The third parameter of is set to true. In general, we don't want to trigger events during the capture phase , So this parameter is generally false.

Common events

Mouse events

Drag events

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box1 {
    
				width: 100px;
				height: 100px;
				background-color: red;
				position: absolute;
			}
			
			#box2 {
    
				width: 100px;
				height: 100px;
				background-color: yellow;
				position: absolute;
				left: 200px;
				top: 200px;
			}
		</style>

		<script type="text/javascript">
			window.onload = function() {
    
				/* *  Drag and drop box1 Elements  * -  Drag and drop process  * 1. When the mouse is pressed over the dragged element , Start dragging  onmousedown * 2. When the mouse moves, the dragged element follows the mouse  onmousemove * 3. When the mouse is released , The dragged element is fixed in the current position  onmouseup */

				// obtain box1 
				var box1 = document.getElementById("box1");
				var box2 = document.getElementById("box2");
				var img1 = document.getElementById("img1");

				// Turn on box1 The drag and drop  
				drag(box1);
				// Turn on box2 Of  
				drag(box2);

				drag(img1);

			};

			/* *  Extract a function specially used to set drag and drop  *  Parameters : Turn on dragged elements  */
			function drag(obj) {
    
				// When the mouse is pressed over the dragged element , Start dragging  onmousedown 
				obj.onmousedown = function(event) {
    

					// Set up box1 Capture all mouse down events  
					/* * setCapture() * -  Only IE Support , But it will not be wrong when calling in Firefox , *  And if you use chrome call , Will report a mistake  */
					/*if(box1.setCapture){ box1.setCapture(); }*/
					obj.setCapture && obj.setCapture();

					event = event || window.event;
					//div The offset   mouse .clentX -  Elements .offsetLeft 
					//div The offset   mouse .clentY -  Elements .offsetTop 
					var ol = event.clientX - obj.offsetLeft;
					var ot = event.clientY - obj.offsetTop;

					// by document Bind one onmousemove event  
					document.onmousemove = function(event) {
    
						event = event || window.event;
						// When the mouse moves, the dragged element follows the mouse  onmousemove 
						// Get the coordinates of the mouse  
						var left = event.clientX - ol;
						var top = event.clientY - ot;

						// modify box1 The location of  
						obj.style.left = left + "px";
						obj.style.top = top + "px";

					};

					// by document Bind a mouse release event  
					document.onmouseup = function() {
    
						// When the mouse is released , The dragged element is fixed in the current position  onmouseup 
						// Cancel document Of onmousemove event  
						document.onmousemove = null;
						// Cancel document Of onmouseup event  
						document.onmouseup = null;
						// When the mouse is released , Cancel the capture of the event  
						obj.releaseCapture && obj.releaseCapture();
					};

					/* *  When we drag and drop the content of a web page , The browser will search the content in the search engine by default , *  This will cause the drag function to be abnormal , This is the default behavior provided by the browser , *  If you don't want this behavior to happen , You can use the return false To cancel the default behavior  * *  But it's right IE8 It doesn't work  */
					return false;
				};
			}
		</script>
	</head>

	<body>
		 I'm a text 
		<div id="box1"></div>
		<div id="box2"></div>
		<img src="img/an.jpg" id="img1" style="position: absolute;" />
	</body>
</html>

Wheel event

onwheel All support

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box1 {
    
				width: 100px;
				height: 100px;
				background-color: red;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
    

				// obtain id by box1 Of div 
				var box1 = document.getElementById("box1");

				// by box1 Bind a mouse wheel scrolling event  
				/* * onmousewheel Mouse wheel scrolling events , Will trigger when the scroll wheel rolls , *  However, Firefox does not support this attribute  * *  Required in Firefox  DOMMouseScroll  To bind scroll events  *  Note that this event needs to pass addEventListener() Function to bind  */

				box1.onmousewheel = function(event) {
    

					event = event || window.event;

					//event.wheelDelta  You can get the scroll direction of the mouse wheel  
					// Roll up  120  Roll down  -120 
					//wheelDelta We don't look at the size of this value , Just look at the positive and negative  

					//alert(event.wheelDelta); 

					//wheelDelta This attribute is not supported in Firefox  
					// Use... In Firefox event.detail To get the direction of scrolling  
					// Roll up  -3  Roll down  3 
					//alert(event.detail); 

					/* *  When the mouse wheel rolls down ,box1 Lengthening  *  When the roller rolls up ,box1 shorter  */
					// Determine the direction in which the mouse wheel rolls  
					if(event.wheelDelta > 0 || event.detail < 0) {
    
						// Roll up ,box1 shorter  
						box1.style.height = box1.clientHeight - 10 + "px";

					} else {
    
						// Roll down ,box1 Lengthening  
						box1.style.height = box1.clientHeight + 10 + "px";
					}

					/* *  Use addEventListener() Method binding response function , Cannot be used when canceling the default behavior return false *  Need to use event To cancel the default behavior event.preventDefault(); *  however IE8 I won't support it event.preventDefault(); This thing , If you call directly, an error will be reported  */
					event.preventDefault && event.preventDefault();

					/* *  When the wheel rolls , If the browser has a scroll bar , The scroll bar scrolls , *  This is the default behavior of browsers , If you don't want it to happen , You can cancel the default behavior  */
					return false;

				};

				// Bind events for Firefox  
				bind(box1, "DOMMouseScroll", box1.onmousewheel);

			};

			function bind(obj, eventStr, callback) {
    
				if(obj.addEventListener) {
    
					// Most browsers are compatible  
					obj.addEventListener(eventStr, callback, false);
				} else {
    
					/* * this Who is determined by the calling method  * callback.call(obj) */
					//IE8 And the following  
					obj.attachEvent("on" + eventStr, function() {
    
						// Callback function is invoked in anonymous function  
						callback.call(obj);
					});
				}
			}
		</script>
	</head>

	<body style="height: 2000px;">

		<div id="box1"></div>

	</body>

</html>

Keyboard events

onkeydown

Indicates that the key is pressed . about onkeydown For example, if you keep pressing a key and don't let go , The event will always trigger . When onkeydown When triggered continuously , The interval between the first and second times will be a little longer , Others will be very fast , This design is to prevent misoperation .

onkeyup

Indicates that the key is released

Keyboard events are usually bound to some objects that can get the focus or document

keyCode

Can pass keyCode To get the code of the key , It can be used to determine which key is pressed .

except keyCode, Several properties are also provided in the event object :altKey、ctrlKey、shiftKey. These three are used to judge alt ctrl and shift Is it pressed

If pressed, return to true, Otherwise return to false

//console.log(event.keyCode); 
  
// Judge a y Is it pressed  
// Judge y and ctrl Whether it is pressed at the same time  
if(event.keyCode === 89 && event.ctrlKey){
    
	console.log("ctrl and y It's all pressed ");
}  
input.onkeydown = function(event) {
      
    event = event || window.event;  
    // Numbers  48 - 57
    // Make it impossible to enter numbers in the text box  
    if(event.keyCode >= 48 && event.keyCode <= 57) {
      
        // Enter content in the text box , Belong to onkeydown Default behavior of  
        // If in onkeydown The default behavior is canceled in , Then enter the content , Does not appear in the text box  
        return false;  
    }  
};

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290808528340.html

Random recommended