当前位置:网站首页>JS basic exercises
JS basic exercises
2022-07-27 08:18:00 【Little bee learns Java】
Change colors between lines (%):
window.onload = function() {
var aLi = document.getElementsByTagName('li');
for(var i = 0; i < aLi.length; i++){
if(i%2 == 1){
aLi[i].style.background = '#bfa';
}
}
}
<ul>
<li>aaa</li>
<li>bbb</li>
<li>ccc</li>
<li>ddd</li>
</ul>
Clean Calculator Beta :
<script> window.onload = function(){
var oNum1 = document.getElementById('num1');
var oNum2 = document.getElementById('num2');
var oBtn = document.getElementById('btn');
var oSel = document.getElementById('sel');
oBtn.onclick = function(){
var iNum1 = parseInt(oNum1.value);
var iNum2 = parseInt(oNum2.value);
switch(oSel.value){
case '+':
alert(iNum1+iNum2);
break;
case '-':
alert(iNum1-iNum2);
break;
case '*':
alert(iNum1*iNum2);
break;
case '/':
alert(iNum1/iNum2);
break;
default:
alert(' You don't have the right operator !');
break;
}
}
}
</script>
<input type="text" id = "num1">
<select name="" id="sel">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2">
<input type="button" value=" Calculation " id="btn">
Bichromatic sphere random number generation :
The goal is : Generate a group of (7 individual ) 1-33 Between random non repeating integers (1. Generate a 1-33 Integer between . 2. Generate 7 individual –> The cycle length is not fixed while loop . 3. Do not repeat , Zero padding operation )
<script>
function rnd(m, n) {
return m + parseInt(Math.random()*(n-m));
}
// Array weight removal
function findInArr(num,arr) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] == num){
return true;
}
}
return false;
}
function toDo(n){
return n < 10 ? '0' + n : '' + n;
}
var arr = [];
while(arr.length < 7) {
//1-34 Include 1, barring 34
var rNum = rnd(1,34);
if(findInArr(rNum,arr) == false) {
arr.push(toDo(rNum));
}
}
document.write(arr);
</script>
The mouse slip div Show hidden :
<div id="box1"
οnmοuseοver="document.getElementById('box1').style.width='200px';document.getElementById('box1').style.height='200px'"
οnmοuseοut="document.getElementById('box1').style.width='100px';document.getElementById('box1').style.height='100px'">
</div>
conditional if:
Click button , If div Show , Then hide it , If div hide , Then show it .
<input type="button" value=" Show hidden " οnclick="showHide()"> <div id="box1"></div> <script> function showHide() {
var oDiv = document.getElementById('box1');
if (oDiv.style.display == "block") {
oDiv.style.display = "none";
} else {
oDiv.style.display = "block";
}
}
</script>
Background color changing function :
One page has two buttons , One div Click on different buttons , The background color changes into different colors , The font size should also be changed .
<style> #box1 {
width: 200px;
height: 200px;
background-color: #bfa;
}
.day{
background: green;
font-size: 10px;
}
.night{
background: gray;
font-size: 22px;
}
</style> <input type="button" value=" Day " οnclick="showDay()"> <input type="button" value=" night " οnclick="showNight()"> <div id="box1"> Realize the skin changing function during the day and night </div> <script> function showDay(){
document.body.className="day";
}
function showNight(){
document.body.className="night";
}
</script>
The separation of behavior and structure :
<script>
window.onload = function(){
//1. Get elements
var oBtn = document.getElementById('btn');
//2. Plus event
oBtn.onclick = function(){
alert();
};
};
</script>
The realization of all selection function :
<script>
window.onload = function () {
var oA = document.getElementById('all');
var oBox = document.getElementById('box');
// Get a set of elements
var oInp = oBox.getElementsByTagName('input');
oA.onclick = function () {
for (var i = 0; i < oInp.length; i++) {
oInp[i].checked = true;
}
};
};
</script>
<input type="button" value=" Future generations " id="all">
<hr>
<div id="box">
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
<input type="checkbox" name="">
</div>
There are two ways to manipulate element content and attributes :
① The way :
window.onload = function(){
var oBtn = document.getElementById('btn');
oBtn.style.background = 'red';
// Mode 2 can realize 1 Functions that can't be realized oBtn['style']['background'] = 'green';
//var aaa = 'background';
//oBtn.style[aaa] = 'green'; Be able to use variables
}
② Content :
- Form Elements :oBtn.value
- Non form elements :
The front-end study
oP.innerHTML
Realization of reverse selection function :
window.onload = function() {
var oR = document.getElementById('reverse');
var oC = document.getElementById('C1');
oR.onclick = function(){
if(oC.checked == true){
oC.checked = false;
}else{
oC.checked = true
}
}
}
<input type = "button" value=" Single check box is inverted " id="reverse">
<input type="checkbox" name="" id="C1">
// It's too troublesome to write like this , It's not simple enough . The changes are as follows :
<script>
window.onload = function() {
var oR = document.getElementById('reverse');
var oC = document.getElementById('C1');
oR.onclick = function() {
oC.checked = !oC.checked;
}
}
</script>
<input type="button" value=" Single check box is inverted " id="reverse">
<input type="checkbox" name="" id="C1">
Linkage selection :
demand : Click Select all above , Then select all the following , If you select all below , Then select , If one of the following is not selected , Then do not select .
<script>
window.onload = function() {
var oA = document.getElementById('all');
var oBox = document.getElementById('box');
var oInp = oBox.getElementsByTagName('input');
oA.onclick = function(){
for(var i = 0; i < oInp.length; i++){
oInp[i].checked = oA.checked;
}
};
for(var i = 0; i < oInp.length; i++){
oInp[i].onclick = function() {
var count = 0;
for(var i = 0; i < oInp.length; i++){
if(oInp[i].checked){
count++;
}
}
if(count == oInp.length){
oA.checked = true;
}else{
oA.checked = false;
}
}
}
}
</script>
<input type="checkbox" name id="all"> Future generations
<hr>
<div id="box">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
// Why do I have to add one box
Tab implementation ( Exclusive thoughts ):
for The cycle is completed in an instant
<style>
#box .on{
background:#bfa;
}
#box div{
width:300px;
height:200px;
border:1px solid red;
display: none;
}
</style>
<script>
window.onload = function(){
var oBox = document.getElementById('box');
var oBtn = oBox.getElementsByTagName('input');
var oDiv = oBox.getElementsByTagName('div');
for(var i = 0; i < oBtn.length; i++){
oBtn[i].index = i;
oBtn[i].onclick = function(){
for(var i = 0; i < oBtn.length; i++){
oBtn[i].className = '';
oDiv[i].style.display = 'none';
}
this.className = 'on';
oDiv[this.index].style.display = 'block';
}
}
}
</script>
<div id = "box">
<input type="button" value=" sports " class="on">
<input type="button" value=" entertainment ">
<input type="button" value=" Journalism ">
<div style="display='block'">*** get 100 Rice first </div>
<div> Duan Yihong is so handsome !</div>
<div> U.S. President Wang was killed at the White House yesterday **</div>
</div>
Simple timer :
<script>
window.onload = function() {
var oTime = document.getElementById('time');
var oStart = document.getElementById('start');
var oStop = document.getElementById('stop');
var timer = null;
function toDo(n){
return n < 10 ? '0' + n : n;
}
oStart.onclick = function() {
var s = 0;
clearInterval(timer);
timer = setInterval(function(){
s++;
oTime.value = toDo(parseInt(s / 60)) + ':' + toDo( s % 60);
},50);
};
oStop.onclick = function() {
clearInterval(timer);
}
};
</script>
<input type = "text" value="00:00" id = "time">
<input type = "button" value=" Start " id="start">
<input type = "button" value = " stop it " id = "stop">
Text clock :
<script>
window.onload = function() {
var oP = document.getElementById('p1');
var timer = null;
function toDo(n) {
return n < 10 ? '0' + n : n;
}
function time() {
var arr = [' Japan ', ' One ', ' Two ', ' 3、 ... and ', ' Four ', ' 5、 ... and ',' 6、 ... and '];
var oDate = new Date();
var year = oDate.getFullYear();
var month = oDate.getMonth() + 1;
var date = oDate.getDate();
var w = oDate.getDay();
var h = oDate.getHours();
var m = oDate.getMinutes();
var s = oDate.getSeconds();
oP.innerHTML = year + ' year ' + month + ' month ' + date + ' Japan ' +toDo(h) +':' + toDo(m) + ':' + toDo(s) + ' week ' + arr[w];
}
time();// You don't need to wait a second to execute the function
clearInterval(timer);// The timer turns off before executing
timer = setInterval(time,1000);
}
</script>
<p id="p1">2020 year 8 month 20 Japan 15:56:30 Thursday </p>
Delay advertising :
picture 2s It shows ,2s Disappear after , When the mouse moves into the picture , Don't disappear , After removal 2s disappear .
Timer can be set inside the timer
<script>
window.onload = function() {
var oImg = document.getElementById('pic');
var timer = null;
var timer2 = null;
clearTimeout(timer);
timer = setTimeout(function(){
oImg.style.display = 'block';
clearTimeout(timer2);
timer2 = setTimeout(function(){
oImg.style.display = 'none';
},2000);
},2000);
oImg.onmouseover= function(){
clearTimeout(timer2);
};
oImg.onmouseout = function(){
timer2 = setTimeout(function(){
oImg.style.display = 'none';
},2000);
};
};
</script>
<img src="../image/1.jpg" id="pic">
Custom properties :
<script>
window.onload = function(){
var oBtn = document.getElementById('btn');
oBtn.abc = 0; // Custom properties
oBtn.onclick = function(){
alert(this.abc);
}
};
</script>
<input type="button" value="aaa" id="btn">
Shuffling figure ( a key ):
<style>
#box .on{
background: #bfa;
}
#box div{
width: 300px;
height: 200px;
border: 1px solid red;
display: none;
}
</style>
<script>
window.onload = function() {
var oBox = document.getElementById('box');
var oPrev = document.getElementById('prev');
var oNext = document.getElementById('next');
var oBtn = oBox.getElementsByTagName('input');
var oDiv = oBox.getElementsByTagName('div');
var iNow = 0;
for(var i = 0; i < oBtn.length; i++){
oBtn[i].index = i;
oBtn[i].onclick = function(){
iNow = this.index;
for(var i = 0; i < oBtn.length; i++){
oBtn[i].className='';
oDiv[i].style.display='none';
}
this.className='on'; //this=oBtn[iNow]
oDiv[this.index].style.display='block';
};
}
// Next play
oNext.onclick = function(){
for(var i = 0; i < oBtn.length; i++){
oBtn[i].className='';
oDiv[i].style.display='none';
}
iNow++;
if(iNow == oBtn.length){
iNow = 0;}
oBtn[iNow].className='on';
oDiv[iNow].style.display='block';
};
// Last play
oPrev.onclick = function(){
for(var i = 0; i < oBtn.length; i++){
oBtn[i].className='';
oDiv[i].style.display='none';
}
iNow--;
if(iNow == -1){
iNow = oBtn.length - 1;}
oBtn[iNow].className='on';
oDiv[iNow].style.display='block';
};
};
</script>
<div id="box">
<a href="javascript:;" id="prev"><-</a>
<input type="button" value="aaa" class="on">
<input type="button" value="bbb">
<input type="button" value="ccc">
<a href="javascript:;" id="next">-></a>
<div style="display:block">aaa</div>
<div>bbb</div>
<div>ccc</div>
</div>
Simplify the code ( encapsulation )+ Realize automatic playback function as follows :
<script>
window.onload = function() {
var oBox = document.getElementById('box');
var oPrev = document.getElementById('prev');
var oNext = document.getElementById('next');
var oBtn = oBox.getElementsByTagName('input');
var oDiv = oBox.getElementsByTagName('div');
var iNow = 0;
var timer = null;
function tab(){
for(var i = 0; i < oBtn.length; i++){
oBtn[i].className='';
oDiv[i].style.display='none';
}
oBtn[iNow].className='on';
oDiv[iNow].style.display='block';
}
for(var i = 0; i < oBtn.length; i++){
oBtn[i].index = i;
oBtn[i].onclick = function(){
iNow = this.index;
tab();
};
}
// Next play
function fnNext(){
iNow++;
if(iNow == oBtn.length){
iNow = 0;}
tab();
}
oNext.onclick = fnNext;
// Last play
oPrev.onclick = function(){
iNow--;
if(iNow == -1){
iNow = oBtn.length - 1;}
tab();
};
// Auto play
clearInterval(timer);
timer = setInterval(function(){
fnNext();
},1000);
oBox.onmouseover = function(){
clearInterval(timer);
};
oBox.onmouseout = function(){
clearInterval(timer);
timer = setInterval(function(){
fnNext();
},1000);
};
};
</script>
Understand the immediate execution of functions :
var a = 12;
alert((a)); //2 Layer brackets do not affect the result
var show = function(){
};
show(); //(show)()
;(function(){
})(); // Prevent others' code from affecting your own
(function(){
var a = b = 10;
})();
console.log(a); //undefined
console.log(b); //10
Simply post a message :
<script>
window.onload = function(){
var oTxt=document.getElementById('txt');
var oBtn=document.getElementById('btn');
var oUl=document.getElementById('ul1');
oBtn.onclick = function(){
var oLi = document.createElement('li');
oLi.innerHTML=oTxt.value;
//oUl.insertBefore(oLi,oUl.children[0]);
// If there is no element under the parent , Then insert backward , Yes , Insert... Forward . compatible IE
if(oUl.children.length == 0){
oUl.appendChild(oLi);
}else{
oUl.insertBefore(oLi,oUl.children[0]);
}
oTxt.value = '';
};
};
</script>
<input type="text" id="txt">
<input type="button" value=" Release " id="btn">
<ul id="ul1"></ul>
Move up and move down :
<script>
window.onload = function(){
var oUl = document.getElementById('ul1');
var aPrev = oUl.getElementsByClassName('prev');
// Move upward
for(var i = 0; i < aPrev.length; i++){
aPrev[i].onclick = function(){
var obj = this.parentNode;
if(obj == oUl.children[0]){
alert(' The end of the ');
return;
}
var oPrev = obj.previousElementSibling || obj.previousSibling;
oUl.insertBefore(obj,oPrev);
};
}
// Move down
var aNext = oUl.getElementsByClassName('next');
for(var i = 0; i < aNext.length; i++){
aNext[i].onclick = function(){
var obj = this.parentNode;
if(obj == oUl.children[oUl.children.length-1]){
alert(' Whether the ');
return;
}
var oNext = obj.nextElementSibling || obj.nextSibling;
var oNext2 = oNext.nextElementSibling || oNext.nextSibling;
oUl.insertBefore(obj,oNext2);
};
}
};
</script>
<ul id="ul1">
<li><span>0. abed, I see a silver light </span>
<a href="javascript:;" class="prev"> Move upward </a>
<a href="javascript:;" class="next"> Move down </a></li>
<li><span>1. The frost on the ground </span>
<a href="javascript:;" class="prev"> Move upward </a>
<a href="javascript:;" class="next"> Move down </a></li>
<li><span>2. look at the bright moon </span>
<a href="javascript:;" class="prev"> Move upward </a>
<a href="javascript:;" class="next"> Move down </a></li>
<li><span>3. Bow your head and think of your hometown </span>
<a href="javascript:;" class="prev"> Move upward </a>
<a href="javascript:;" class="next"> Move down </a></li>
</ul>
The function of suspension box in the lower right corner is realized :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-SwhN8Ctu-1598018747062)(C:\Users\Hrj201305042\AppData\Roaming\Typora\typora-user-images\image-20200821143137668.png)]
// The distance actually occupied by the object
window.onload = function(){
var oDiv = document.getElementById('div1');
alert(oDiv.offsetHeight);
};
// About the rolling distance
body{
height:3000px;}
#btn{
position:fixed; left:10px; top:200px;}
window.onscroll = function(){
var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
var sT = document.documentElement.scrollTop || document.body.scrollTop;
alert(sT);
};
};
// The height of the viewing area
window.onload = function(){
var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
alert(document.documentElement.clientHeight);
};
};
<script> // The window shrinks onresize
window.onresize = window.onload=window.onscroll=
function(){
if(window.navigator.userAgent.indexOf('MSIE 6.0')!=-1){
var oDiv = document.getElementById('div1');
var sT = document.documentElement.scrollTop || document.body.scrollTop;
var cH = document.documentElement.clientHeight;
var oH = oDiv.offsetHeight;
oDiv.style.top = sT + cH + oH +'px';
}
};
</script>
<div id="div1"></div>
json The difference with arrays :
json Each element in is indexed by a string , Arrays are indexed by numbers .json Use for in loop , Arrays generally use for loop .
var json = {
"name":"leo", "age":18}; var arr=["leo",18];
json It's a data format , and JavaScript No direct contact ,js Native provides some json Operation method , yes js One of the most common data formats for data interaction
json And string :① String rotation json:name=leo&age=18 => {“name”: “leo”, “age” : 18}
<script>
function url2json(str){
var arr = str.split('&');
var json = {
};
for(var i = 0; i < arr.length; i++){
//[user = leo age = 18 class = javas]
//arr[i].split('=')[0] user
//arr[i].split('=')[1] leo
//json['user'] = leo
json[arr[i].split('=')[0]] = arr[i].split('=')[1];
}
return json
}
var str = 'user=leo&age=18&class=javas';
console.log(url2json(str));
</script>
②json Turn the string {“name”: “leo” , “age” : 18} => name=leo&age=18
function json2url(json){
var arr = [];
for(var name in json){
//name user
//json[name] leo
arr.push(name + '=' + json[name]);
['name=leo', 'age=18']
}
return arr.join('&');
}
var json = {
user:"leo", age:18, class:"javas"};
alert(json2url(json));
Text input box prompt implementation :
#box{
position:relative;}
#box span{
color:#ccc;position:absolute;left:6px;top:2px;}
<script>
window.onload = function(){
var oS = document.getElementById('s1');
var oTxt = document.getElementById('txt');
oTxt.onfocus = function(){
oS.style.display = 'none';
};
oTxt.onblur = function(){
if(oTxt.value == ''){
oS.style.display = 'block';
}
};
oS.onclick = function(){
//oS.style.display = 'none';
oTxt.focus();
};
};
</script>
<div id="box">
<span id="s1"> Please enter the content </span>
<input type="text" id="txt">
</div>
Event object :
<script>
window.onload = function(){
var oBtn = document.getElementById('btn');
oBtn.onclick = function(ev){
var oEvent = ev||event;
console.log(oEvent);
};
};
</script>
<input type="button" value=" Click on " id="btn">
Event Bubbling :
document.onclick = function(){
alert('document');};
<div id="div1" onclick="alert('div1')">
<input type="button" value=" Button " onclick="alert('input')">
</div> // Click button , From the inside out ,input->div1->document.
//( The parent also uploads without events ) If input My superior div Do not add events input-> document
// Cancel the bubbling :1 standard :oEvent.stopPropagation&&oEvent.stopPropagation();
2.IE: oEvent.cancelBubble&&(oEvent.cancelBubble=true);
// The binding event :FF chrome
oBtn.addEventListener('click',aaa,false);
//IE6-8 There is no capture phase , Only bubbles
oBtn.attachEvent('onclick', aaa;
Get the mouse click position :
document.onclick = function(){
//chrome , IE
alert('left:' + event.clientX+',top:'+event.clientY);
};
div Follow the mouse :
Mouse movement ,div Follow the mouse
Realization :1. Get mouse position 2. Assign a value to div Of left and top style
#div1{
width:200px;height:200px;background:#bfa;position:absolute;}
<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
document.onmousemove = function(ev){
var oEvent = ev || event;
console.log('ev.clientX:' + oEvent.clientX + 'ev.clientY:' + oEvent.clientY);
oDiv.style.left = oEvent.clientX + 'px';
oDiv.style.top = oEvent.cilentY + 'px';
};
};
</script>
<div id="div1"></div>
边栏推荐
- 一文速览EMNLP 2020中的Transformer量化论文
- Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
- How does kettle handle text data transfer as' 'instead of null
- Apache SSI remote command execution vulnerability
- Use of "PHP Basics" delimiters
- 帮忙发几个招聘,有兴趣可以看看
- The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions
- [target detection] yolov6 theoretical interpretation + practical test visdrone data set
- [applet] the upload of the wechat applet issued by uniapp failed error: error: {'errcode': -10008,'errmsg':'Invalid IP
- Five day travels to Beijing
猜你喜欢
![[ten thousand words long article] thoroughly understand load balancing, and have a technical interview with Alibaba Daniel](/img/fc/1ee8b77d675e34da2eb8574592c489.png)
[ten thousand words long article] thoroughly understand load balancing, and have a technical interview with Alibaba Daniel

DEMO:ST05 找文本ID 信息

Risk control and application of informatization project

开怀一笑

Attack and defense world MFW

Prevent cookies from modifying ID to cheat login

OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)

How to log in multiple wechat on the computer

百人参与,openGauss开源社区这群人都在讨论什么?

Vcenter7.0 managing esxi7.0 hosts
随机推荐
pytorch_ demo1
How to log in multiple wechat on the computer
A quick overview of transformer quantitative papers in emnlp 2020
信息化项目风险控制与应用
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation
"PHP Basics" PHP statements and statement blocks
QingChuang technology joined dragon lizard community to build a new ecosystem of intelligent operation and maintenance platform
Development of three database general SQL code based on PG Oracle and MySQL
数据提取1
Data extraction 1
Comprehensive cases
阿里云国际版回执消息简介与配置流程
Leetcode56. Consolidation interval
Translation character '/b' in C #
All in one 1319 - queue for water
How to analyze and locate problems in 60 seconds?
Vcenter7.0 installation of ibm3650m4 physical machine
Opengauss stopped from the library and found that the main library could not write data
Idea remote debugging
idea远程调试