id,class,css选择器
实例
<!doctype html> <html> <head> <meta charset="utf-8"> <title>选择元素</title> </head> <body> <ul id="top"> <li class="bottom">1</li> <li class="mid">2</li> <li>3</li> </ul> <script> //通过ID名 let ul = document.getElementById('top'); ul.style.background = 'red'; //通过标签名 let li = document.getElementsByTagName('li')[2]; li.style.background = 'blue'; //CSS选择器,querySlelector返回的是一个数组 let list = document.querySelectorAll('li'); list[0].style.background = 'green'; //通过id选择器选择 let id1 = document.querySelector('#top'); id1.style.background = '#ccc'; //通过class选择器选择 let class1 = document.querySelector('.mid'); class1.style.color = 'grey'; </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
在线聊天机器人
实例
<!doctype html> <html> <head> <meta charset="utf-8"> <title>自动聊天机器人</title> <style> .box{width: 400px;height: 615px;background: #826858;box-shadow: 2px 2px 2px grey;margin: auto} .top{width: 380px;height: 50px;background: #fedcbd;margin: 5px auto;text-align: center;line-height: 50px} .mid{width: 380px;height: 470px;background: #deab8a;margin: 5px auto} .bottom{width: 380px;height: 70px;background: #ca8687;margin: 5px auto} .list{margin: 0;list-style: none} </style> </head> <body> <div class="box"> <div class="top"><h2>黄凯</h2></div> <div class="mid"> <ul class="list"> </ul> </div> <div class="bottom"> <textarea name="" id="" cols="42" rows="4"></textarea> <button type="button" style="display: inline-block;line-height: 50px;position: absolute ;margin-top: 7px;margin-left: 5px">发送</button> </div> </div> </body> <script> let list = document.getElementsByTagName('ul')[0]; let text = document.getElementsByTagName('textarea')[0]; let btn = document.getElementsByTagName('button')[0]; btn.onclick = function(){ let userTalk = text.value; let li = document.createElement('li'); li.style.textAlign = 'right'; let img = '<img src="1.png" width="30" style="border-radius:50%"></img>' li.innerHTML = userTalk+img ; list.appendChild(li); text.value = ''; setTimeout(function(){ let rep = '帅死了'; let img = '<img src="2.jpg" width="30" style="border-radius:50%"></img>'; let li = document.createElement('li'); li.innerHTML = img + rep; list.appendChild(li); },1000) } </script> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
个人总结:
个人觉得,选择器虽然多种多样,但只需要记住其中经常用到的几种就可以了。
尤其需要记住,appendChild(),括号内的元素不用加''!!!