天使跟随鼠标案例
实现核心思路:
- 鼠标不断的移动,使用鼠标移动时间:mousemove
- 在页面中移动,给document注册事件
- 图片要移动距离,而且不占位置,我们使用绝对定位即可
- 核心原理:每次鼠标移动,我们都会获得最新的鼠标坐标,把这个X和Y坐标作为图片的left和top值就可以移动图片
实现代码:
<style type="text/css">
body{
position: relative;
background-color: #1b1b1b;
}
img{
width: 60px;
height: 60px;
position: absolute;
}
</style>
</head>
<body>
<img src="img/天使.gif"/>
</body>
<script type="text/javascript">
var logo = document.querySelector('img'); ---给document注册鼠标移动事件---
document.addEventListener('mousemove',function(e) {
var x = e.pageX; ---获取鼠标的X,Y坐标 这里坐标是相对于整个文档页面的 用e.page
var y = e.pageY;
logo.style.left = x - 40 + 'px'; ---将坐标值给图片定位的left和top---
logo.style.top = y - 40 + 'px';
})
</script>
实现效果:
输入框放大提示文本内容
核心思路:
- 快递单号输入内容时,上面的大号字体盒子内的提示文本的字体字号更大
- 表单检测用户输入:给表单添加键盘事件
- 同时把快递单号里面的值(value)获取过来赋值给提示文本盒子(innerText)作为内容
- 如果快递单号里面内容为空,则隐藏提示文本的盒子
- 注意:keydown 和 keypress 在文本框里面的特点:他们两个事件触发的时候i,文字还没有落入文本框中。这个案例中需要用keyup。
- keyup事件触发的时候,文字已经落入文本框里面了。
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box{
width: 400px;
height: 400px;
margin: 0 auto;
position: relative;
border: 1px solid purple;
}
.title{
width: 220px;
height: 40px;
position: absolute;
left: 50px;
top: 150px;
background-color: gainsboro;
display: none;
font-size: 24px;
line-height: 40px;
color: deeppink;
}
.title::after{
content: "";
width: 0;
height: 0;
background-color: blueviolet;
display: block;
position: absolute;
bottom: -10px;
left: 10px;
border-top: 5px solid gainsboro;
border-left: 4px solid white;
border-right: 4px solid white;
border-bottom: 5px solid white;
}
input{
width: 200px;
height: 20px;
position: absolute;
top: 200px;
left: 50px;
line-height: 20px;
}
button{
position: absolute;
right: 75px;
bottom: 175px;
}
</style>
</head>
<body>
<div class="box">
<div class="title"></div>
<input type="text" placeholder="请输入快递单号"/>
<button>查询</button>
</div>
</body>
<script type="text/javascript">
var ipt = document.querySelector('input'); ---获取输入框和提示框---
var tit = document.querySelector('.title');
document.addEventListener('keyup', function(e) { ---给document注册键盘事件---
if (e.keyCode == 13) { ---设定当按下enter键时 自动聚焦输入框---
ipt.focus();
}
if (ipt.value != '') { ---判断,如果输入框内容不为空,则显示提示框并且把输入框内容给提示框---
tit.style.display = 'block';
tit.innerHTML = ipt.value;
} else {
tit.style.display = 'none'; ---如果输入框内容为空,则隐藏提示框---
}
})
</script>
</html>
下面是实现效果:
进行键盘事件测试:
只有按下enter 键才会输入框聚焦
输入提示文本后,显示提示文本:
键盘聚焦搜索框
e.keyCode用来判断返回按下的键的ascii值
</style>
</head>
<body>
<input type="text" />
</body>
<script type="text/javascript">
var ipt = document.querySelector('input');
document.addEventListener('keyup',function(e) {
console.log(e.keyCode);
if(e.keyCode == 13) {
ipt.focus();
}
})
</script>
这里还是用keyup来实现;