<div id="time">2020-9-27</div>
<script>
//文档页面从上往下加载,先有标签才能获取元素对象,script写到标签的后面
// get获得element元素by通过驼峰命名法
//参数id是大小写敏感的字符串
//返回的是一个元素对象
var timer = document.getElementById('time');
console.log(timer);
console.log(typeof timer);
console.dir(timer);
</script>
排他算法
var btnLis = document.querySelectorAll('button');
for (var i = 0; i < btnLis.length; i++) {
btnLis[i].onclick = function () { for (var j = 0; j < btnLis.length; j++) {
btnLis[j].style.backgroundColor = '';
} this.style.backgroundColor = 'red';
}
}
复选框与全选的实现
<input type="checkbox" id='all'>全选</input>
<input type="checkbox" class='a'>单独</input>
<input type="checkbox" class='a'>单独</input>
<input type="checkbox" class='a'>单独</input>
<input type="checkbox" class='a'>单独</input>
<script>
var cbLis = document.getElementsByClassName('a');
var cbAll = document.getElementById('all'); cbAll.onclick = function () { //全选控制
for (var i = 0; i < cbLis.length; i++) {
cbLis[i].checked = this.checked;
}
} for (var i = 0; i < cbLis.length; i++) { //子选框控制全选按钮
cbLis[i].onclick = function () {
var flag = true;
for (var i = 0; i < cbLis.length; i++) {
if (cbLis[i].checked == false) {
flag = false;
break;
}
}
cbAll.checked = flag;
}
}
</script>
论坛发布评论实现
<textarea name="" id="" cols="30" rows="10">123</textarea>
<button>发布</button>
<ul>
</ul> <script>
//获取元素对象
var btn = document.querySelector('button');
var text = document.querySelector('textarea');
var ul = document.querySelector('ul'); btn.onclick = function () { //发布按钮点击事件
if (text.value == '') {
alert('没有输入内容');
return false;
} else {
var li = document.createElement('li');
li.innerHTML = text.value + "<a href='javascript:;'>删除</a>";
ul.insertBefore(li, ul.children[0]);
} var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function () { //删除链接点击事件
ul.removeChild(this.parentNode);
}
}
}
鼠标移动天使跟随案例
<style>
body {
background-color: black;
} img {
position: absolute;
width: 200px;
}
</style> <body>
<img src="../images/pic.gif" alt="">
</body>
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function (e) {
var x = e.pageX;
var y = e.pageY;
pic.style.left = (x - 100) + 'px';
pic.style.top = (y - 75) + 'px'; })
</script>
鼠标按s光标到文本框内
<body>
<input type="text"> <script>
var search = document.querySelector('input');
document.addEventListener('keyup', function (e) {
if (e.keyCode === 83) {
search.focus();
}
})
</script>
</body>
倒计时隐藏盒子
<body>
<input type="text"> <script>
var search = document.querySelector('input');
setTimeout(function () {
search.style.display = 'none';
}, 3000)
</script>
</body>