current position:Home>5. Operation element
5. Operation element
2022-01-27 07:30:31 【Bald girl in study】
5、 Operational elements
JavaScript Of DOM The operation can change the content of the web page 、 Structure and pattern , We can use DOM Manipulate elements to change the contents of elements 、 Properties, etc .( Be careful : These operations are implemented through the attributes of the element object )
1. Change element content ( Get or set )
innerText Change element content
<button> Display the current system time </button>
<div> Some time </div>
<p>123</p>
<script>
// Click button ,div The text will change
// 1. Get elements
var btn = document.querySelector('button');
var div = document.querySelector('div');
// 2. Registration events
btn.onclick = function() {
div.innerHTML = getDate();
}
function getDate() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '];
var day = date.getDay();
return ' It's today :' + year + ' year ' + month + ' month ' + dates + ' Japan ' + arr[day];
}
</script>
</body>
innerText and innerHTML The difference between
- The difference in getting content :
innerText Will remove spaces and line breaks , and innerHTML Spaces and line breaks are preserved
- The difference when setting content :
innerText Can't recognize html, and innerHTML identifies
Case code
<body>
<div></div>
<p>
I am character.
<span>123</span>
</p>
<script>
// Elements can be added without adding events , Direct change
// var p = document.querySelector('p');
// p.innerHTML = getDate();
// innerText and innerHTML The difference between
// 1. innerText Don't recognize html label Nonstandard Will remove spaces and line breaks
var div = document.querySelector('div');
div.innerText = '<strong> It's today :</strong> 2019';
// 2. innerHTML distinguish html label W3C standard Spaces and line breaks are preserved
div.innerHTML = '<strong> It's today :</strong> 2019';
// These two properties are readable and writable You can get the content of the element
var p = document.querySelector('p');
console.log(p.innerText);
console.log(p.innerHTML);
</script>
</body>
2. Attribute operation of common elements
Get the value of the property
Element object . Property name
Set the value of the property
Element object . Property name = value
Case code
<body>
<button id="ldh"> Lau Andy </button>
<button id="zxy"> Jacky Cheung </button> <br>
<img src="images/ldh.jpg" alt="" title=" Lau Andy ">
<script>
// Modify element properties src
// 1. Get elements
var ldh = document.getElementById('ldh');
var zxy = document.getElementById('zxy');
var img = document.querySelector('img');
// 2. Registration events The handler
zxy.onclick = function() {
img.src = 'images/zxy.jpg';
img.title = ' Jacky Cheung ';
}
ldh.onclick = function() {
img.src = 'images/ldh.jpg';
img.title = ' Lau Andy ';
}
</script>
</body>
Case study : Time sharing greetings
<body>
<img src="images/s.gif" alt="">
<div> Good morning </div>
<script>
// It should be judged according to the different time of the system , So you need to use the date built-in object
// Use multi branch statements to set different pictures
// Need a picture , And modify the picture according to the time , You need to use operation elements src attribute
// Need one div Elements , Show different greetings , Modify the element content
// 1. Get elements
var img = document.querySelector('img');
var div = document.querySelector('div');
// 2. Get the current number of hours
var date = new Date();
var h = date.getHours();
// 3. Determine the number of hours, change pictures and text messages
if (h < 12) {
img.src = 'images/s.gif';
div.innerHTML = ' Pro - , Good morning , Write good code ';
} else if (h < 18) {
img.src = 'images/x.gif';
div.innerHTML = ' Pro - , Good afternoon, , Write good code ';
} else {
img.src = 'images/w.gif';
div.innerHTML = ' Pro - , Good evening , Write good code ';
}
</script>
</body>
3. Attribute operations of form elements
Get the value of the property
Element object . Property name
Set the value of the property
Element object . Property name = value
There are some attributes in form elements such as :disabled、checked、selected, The values of these attributes of the element object are Boolean .
Case code
<body>
<button> Button </button>
<input type="text" value=" Input content ">
<script>
// 1. Get elements
var btn = document.querySelector('button');
var input = document.querySelector('input');
// 2. Registration events The handler
btn.onclick = function() {
// The values in the form The text is written through value To modify
input.value = ' By clicking the ';
// If you want a form to be disabled No more clicks disabled We want this button button Ban
// btn.disabled = true;
this.disabled = true;
// this It points to the caller of the event function btn
}
</script>
</body>
Case study : Copy Jingdong display password
<body>
<div class="box">
<label for="">
<img src="images/close.png" alt="" id="eye">
</label>
<input type="password" name="" id="pwd">
</div>
<script>
// 1. Get elements
var eye = document.getElementById('eye');
var pwd = document.getElementById('pwd');
// 2. Registration events The handler
var flag = 0;
eye.onclick = function() {
// After one click ,flag Be sure to change , When you need to click a button many times, use flag Variable
if (flag == 0) {
pwd.type = 'text';
eye.src = 'images/open.png';
flag = 1; // Assignment operation
} else {
pwd.type = 'password';
eye.src = 'images/close.png';
flag = 0;
}
}
</script>
</body>
4. Style property operation
We can go through JS Change the size of the element 、 Color 、 Position, etc .
Commonly used way
The way 1: By manipulating the style attribute
Element object style Property is also an object !
Element object .style. Style attribute = value ;
Case code
<body>
<div></div>
<script>
// 1. Get elements
var div = document.querySelector('div');
// 2. Registration events The handler
div.onclick = function() {
// div.style The properties inside Take the hump nomenclature
this.style.backgroundColor = 'purple'; // Inline style , Weight high
this.style.width = '250px';
}
</script>
</body>
Case study : Taobao Click to close the QR code
<body>
<div class="box">
Taobao QR code
<img src="images/tao.png" alt="">
<i class="close-btn">×</i>
</div>
<script>
// 1. Get elements
var btn = document.querySelector('.close-btn');
var box = document.querySelector('.box');
// 2. Registration events process
btn.onclick = function() {
box.style.display = 'none';
}
</script>
</body>
Case study : Loop sprite background
<body>
<div class="box">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
// Get all small li
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
// Index number multiplication 44 It's every one li The background of y coordinate
var index = i * 44; // y coordinate
lis[i].style.backgroundPosition = '0 -' + index + 'px';
}
</script>
</body>
Case study : Show hidden text box content
<body>
<input type="text" value=" mobile phone ">
<script>
// 1. Get elements
var text = document.querySelector('input');
// 2. Registration events Get focus event onfocus
text.onfocus = function() {
// console.log(' Got the focus ');
if (this.value === ' mobile phone ') {
this.value = '';
}
// To get focus, you need to darken the text color in the text box
this.style.color = '#333';
}
// 3. Registration events Loss of focus event onblur
text.onblur = function() {
// console.log(' Lost focus ');
if (this.value === '') {
this.value = ' mobile phone ';
}
// To lose focus, you need to lighten the text color in the text box
this.style.color = '#999';
}
</script>
</body>
The way 2: By manipulating the className attribute
Element object .className = value ;
because class Is the key word , All use className.
Case code
<body>
<div class="first"> Text </div>
<script>
// 1. element.style be used for There are few styles or simple functions
var test = document.querySelector('div');
test.onclick = function() {
// this.style.backgroundColor = 'purple';
// this.style.color = '#fff';
// this.style.fontSize = '25px';
// this.style.marginTop = '100px';
// Change the class name of the current element to change
// 2. By modifying the className Changing the style of an element is suitable for situations with many styles or complex functions
// this.className = 'change';
// 3. If you want to keep the original class name , Multiple class name selectors can be used
this.className = 'first change';
}
</script>
</body>
Case study : Password box format prompt error message
<body>
<div class="register">
<input type="password" class="ipt">
<p class="message"> Please enter 6~16 Bit code </p>
</div>
<script>
// The first event to judge is that the form loses focus onblur
// If the input is correct, the correct information will be prompted. The color is green and the small icon changes
// If the input is not 6 To 16 position , The color of the error message is red Small icon changes
// Because there are many styles in it , We take className Modify the style
// 1. Get elements
var ipt = document.querySelector('.ipt');
var message = document.querySelector('.message');
//2. Registration events Lose focus
ipt.onblur = function() {
// According to the length of the value in the form ipt.value.length
if (this.value.length < 6 || this.value.length > 16) {
// console.log(' error ');
message.className = 'message wrong';
message.innerHTML = ' The number of digits you entered is not required 6~16 position ';
} else {
message.className = 'message right';
message.innerHTML = ' Your input is correct ';
}
}
</script>
</body>
copyright notice
author[Bald girl in study],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270730260213.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- I don't know how to start this
guess what you like
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
-
Springboot implements excel import and export, which is easy to use, and poi can be thrown away
-
The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
Random recommended
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of k8s management tool kubectl
- Android system view memory command