目录
案例一:图片跟着鼠标移动
分析:
- 鼠标不断的移动,使用鼠标移动事件:mousemove
- 在页面中移动,给document注册事件
- 图片要移动距离,且不占位置,我们使用绝对定位即可
- 核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个x和y坐标作为图片的top和left值就可以移动图片。【在改变top和left值时,记得在x和y后面加单位 ‘px’】
CSS:
<style>
img{
position: absolute;
transform: translate(-50%,-50%);
}
</style>
HTML+JS:
<img src="./img/CUTE.jpg" width="100px">
<script>
document.addEventListener('mousemove',function(e){
var img =document.querySelector('img')
var x = e.pageX;
var y = e.pageY;
img.style.left = x + 'px';
img.style.top = y + 'px';
})
</script>
效果图:
在这里有一点需要注意的点,如果我们的图片还可以给它固定定位。
但如果我们使用固定定位,横纵坐标还用e.pageX和e.pageY的话,会受到滚轮的影响;而clientX、clientY不会受滚轮的影响 ,所以我们在使用固定定位时,横纵坐标记得要使用clientX、clientY。
案例二:留言板
分析:
- 当我们没有在输入框中输入内容时,点击提交按钮会有弹窗
- 创建节点,给新节点添加内容(包括“删除”超链接),把新节点添加到父节点上,清空输入框的内容
- 先判断留言区有没有可以删除的留言,如果没有,弹窗提示
- 删除想要去除的那一条留言
CSS:
<style>
* {
margin: 0;
padding: 0;
}
body{
background-color: whitesmoke;
}
.box {
width: 500px;
margin: auto;
height: 100px;
}
.box textarea {
width: 100%;
height: 100%;
border: none;
margin-top: 10px;
border-radius: 9px;
background-color: rgb(241, 227, 210);
box-shadow: 2px 2px rgb(201, 200, 200);
}
ul li {
list-style: none;
height: 35px;
line-height: 35px;
background-color: rgb(244, 237, 228);
}
li a{
float: right;
color: #999;
text-decoration: none;
}
li a:hover{
color: red;
}
button{
width: 80px;
height: 25px;
float: right;
color: brown;
font-weight: 600;
cursor: pointer;
border-radius: 3px;
border: none;
background-color: bisque;
margin-top: 5px;
}
h3{
margin: 30px 0;
}
</style>
HTML+JS:
<body>
<div class="box">
<textarea></textarea>
<button>提交留言</button>
<h3>留言区:</h3>
<ul></ul>
</div>
<script>
var btn = document.querySelector('button')
var ulNode = document.querySelector('ul')
var msg = document.querySelector('textarea')
btn.onclick = function () {
if (msg.value == '') {
alert('你当前没有输入任何内容')
}else{
//创建一个节点
var li = document.createElement('li')
//给节点添加内容
li.innerHTML = msg.value+"<a href='javascript:;'>删除</a>"
//添加节点
ulNode.appendChild(li)
//清除文本框的内容
msg.value = ''
}
//删除节点
if(ulNode.children.length == 0){
alert('你当前没有添加内容')
return false
}else{
ulNode.addEventListener('click',function(e){
if(e.target.nodeName == 'A'){
ulNode.removeChild(e.target.parentNode)
}
})
}
}
</script>
</body>
效果: