> 文章列表 > 记录-js基础练习题

记录-js基础练习题

记录-js基础练习题

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

隔行换色(%):

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>

简易计算器:

<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('你没有合适的运算符!');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="计算" id="btn">

双色球随机数生成:

目标:生成一组(7个) 1-33之间的随机不重复的整数(1.生成一个1-33之间的整数。 2.生成7个–>循环长度不固定用while循环。 3.要求不重复,补零操作)

<script>function rnd(m, n) {return m + parseInt(Math.random()*(n-m));}//数组去重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包括1,不包括34var rNum = rnd(1,34);if(findInArr(rNum,arr) == false) {arr.push(toDo(rNum));}}document.write(arr);
</script>

鼠标滑过div显示隐藏:

<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>

条件判断if:

点击按钮,如果div显示,那么隐藏它,如果div隐藏,那么显示它。

<input type="button" value="显示隐藏" ο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>

背景色换肤功能

一个页面两个按钮,一个div点击不同的按钮,背景色分别变成不同的颜色,字体大小也要改变。

<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="白天" οnclick="showDay()">
<input type="button" value="夜晚" οnclick="showNight()">
<div id="box1">实现白天夜晚换肤功能</div>
<script>function showDay(){document.body.className="day";   }function showNight(){document.body.className="night";}
</script>

行为和结构的分离:

<script>window.onload = function(){//1.获取元素var oBtn = document.getElementById('btn');//2.加事件oBtn.onclick = function(){alert();};};
</script>

全选功能的实现:

<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 = true;}};
};
</script>
<input type="button" value="全选" id="all">
<hr>
<div id="box"><input type="checkbox" name=""><input type="checkbox" name=""><input type="checkbox" name=""><input type="checkbox" name="">
</div>

操作元素类容和属性的两种方式:

①方式:

window.onload = function(){var oBtn = document.getElementById('btn');oBtn.style.background = 'red';//方式二能实现1实现不了的功能oBtn['style']['background'] = 'green';//var aaa = 'background';//oBtn.style[aaa] = 'green';能够使用变量
}

②内容:

  1. 表单元素:oBtn.value
  2. 非表单元素:

    前端学习

    oP.innerHTML

反选功能实现:

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="单个复选框反选" id="reverse">
<input type="checkbox" name="" id="C1">//这样写太麻烦了,不够简洁。改变如下:
<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="单个复选框反选" id="reverse">
<input type="checkbox" name="" id="C1">

联动选择:

需求:点击上面的全选,那么下面都选中,如果下面全选中,那么上面也选中,如果下面有一个没选中,那么上面不选中。

<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">全选
<hr>
<div id="box"><input type="checkbox"><input type="checkbox"><input type="checkbox">
</div>
//为什么必须加一个box

选项卡实现(排他思想):

for循环是一瞬间完成的

<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="体育" class="on"><input type="button" value="娱乐"><input type="button" value="新闻"><div style="display='block'">*获得100米第一</div><div>段奕宏真帅!</div><div>美国懂王昨日于白宫遭</div>
</div>

简易定时器:

<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="开始" id="start">
<input type = "button" value = "停止" id = "stop">

文字时钟:

<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 = ['日', '一', '二', '三', '四', '五','六'];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 + '年' + month + '月' + date + '日' +toDo(h) +':' + toDo(m) + ':' + toDo(s) + '星期' + arr[w]; }time();//不需要等一秒钟再执行函数clearInterval(timer);//定时器先关闭再执行timer = setInterval(time,1000);    	}
</script>
<p id="p1">2020年8月20日15:56:30星期四</p>

延迟广告:

图片2s后显示,2s后消失,当鼠标移入图片时,不消失,移出后2s消失。

定时器里面可以套定时器

<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">

自定义属性:

<script>window.onload = function(){var oBtn = document.getElementById('btn');oBtn.abc = 0; //自定义属性oBtn.onclick = function(){alert(this.abc);}};
</script>
<input type="button" value="aaa" id="btn">

轮播图(重点):

<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';};}//下一个播放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';};//上一个播放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>

简化代码(封装)+ 实现自动播放功能 如下:

<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();};}//下一个播放function fnNext(){iNow++;if(iNow == oBtn.length){iNow = 0;}tab();}oNext.onclick = fnNext;//上一个播放oPrev.onclick = function(){			iNow--;if(iNow == -1){iNow = oBtn.length - 1;}tab();};//自动播放clearInterval(timer);timer = setInterval(function(){fnNext();},1000);oBox.onmouseover = function(){clearInterval(timer);};oBox.onmouseout = function(){clearInterval(timer);timer = setInterval(function(){fnNext();},1000);  };};
</script>

理解立即执行函数:

var a = 12;
alert((a)); //2层括号不影响结果
var show = function(){};
show(); //(show)()
;(function(){})();  //防止别人的代码影响自己的(function(){var a = b = 10;
})();
console.log(a); //undefined
console.log(b); //10

简易发布留言:

<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]);//如果父级下面没有元素,那么向后插入,有,则向前插入。兼容IEif(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="发布" id="btn">
<ul id="ul1"></ul>

上移下移功能实现:

<script>window.onload = function(){var oUl = document.getElementById('ul1');var aPrev = oUl.getElementsByClassName('prev');//上移for(var i = 0; i < aPrev.length; i++){aPrev[i].onclick = function(){var obj = this.parentNode;if(obj == oUl.children[0]){alert('到头了');return;}var oPrev = obj.previousElementSibling || obj.previousSibling;oUl.insertBefore(obj,oPrev);};}//下移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('到底了');return;}var oNext = obj.nextElementSibling || obj.nextSibling;var oNext2 = oNext.nextElementSibling || oNext.nextSibling;oUl.insertBefore(obj,oNext2);};}};
</script>
<ul id="ul1"><li><span>0.床前明月光</span><a href="javascript:;" class="prev">上移</a><a href="javascript:;" class="next">下移</a></li><li><span>1.疑是地上霜</span><a href="javascript:;" class="prev">上移</a><a href="javascript:;" class="next">下移</a></li><li><span>2.举头望明月</span><a href="javascript:;" class="prev">上移</a><a href="javascript:;" class="next">下移</a></li><li><span>3.低头思故乡</span><a href="javascript:;" class="prev">上移</a><a href="javascript:;" class="next">下移</a></li>	
</ul>

右下角悬浮框功能实现:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SwhN8Ctu-1598018747062)(C:\\Users\\Hrj201305042\\AppData\\Roaming\\Typora\\typora-user-images\\image-20200821143137668.png)]

//物体实际占的距离
window.onload = function(){var oDiv = document.getElementById('div1');alert(oDiv.offsetHeight);
};
//关于滚动的距离
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);};
};
//可视区的高度
window.onload = function(){var oBtn = document.getElementById('btn');oBtn.onclick = function(){alert(document.documentElement.clientHeight);	};
};
<script>  //窗口缩小onresizewindow.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和数组的区别:

json中每个元素是以字符串作为下标,数组则是以数字作为下标。json使用for in循环,数组一般使用for循环。

var json = {"name":"leo", "age":18};  var arr=["leo",18];

json是种数据格式,和JavaScript没有直接联系,js原生提供了部分json操作方法,是js数据交互最通用的数据格式之一

json和字符串互转:

①字符串转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'] = leojson[arr[i].split('=')[0]] = arr[i].split('=')[1];}return json}var str = 'user=leo&age=18&class=javas';console.log(url2json(str));
</script>

②json转字符串{“name”: “leo” , “age” : 18} => name=leo&age=18

function json2url(json){var arr = [];for(var name in json){//name user//json[name] leoarr.push(name + '=' + json[name]);['name=leo', 'age=18']}return arr.join('&');
}
var json = {user:"leo", age:18, class:"javas"};
alert(json2url(json));

文字输入框提示实现:

#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">请输入内容</span><input type="text" id="txt">
</div>

事件对象:

<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="点击" id="btn">

事件冒泡:

document.onclick = function(){alert('document');};
<div id="div1" onclick="alert('div1')"><input type="button" value="按钮" onclick="alert('input')">
</div> //点击按钮,从里往外传,input->div1->document.//(父级没有事件也往上传)如果input的上级div不添加事件 input-> document//取消冒泡:1标准:oEvent.stopPropagation&&oEvent.stopPropagation();2.IE: oEvent.cancelBubble&&(oEvent.cancelBubble=true);//绑定事件:FF chromeoBtn.addEventListener('click',aaa,false);
//IE6-8 没有捕获阶段,只有冒泡
oBtn.attachEvent('onclick', aaa;

获取鼠标点击位置:

document.onclick = function(){//chrome , IEalert('left:' + event.clientX+',top:'+event.clientY);
};

div跟随鼠标移动:

鼠标移动,div跟随鼠标移动

实现:1.获取鼠标位置 2.赋值给div的left和top样式

#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>

本文转载于:

https://blog.csdn.net/qq_48687155/article/details/108159063

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。