36.一些事件函数

  • 移入【over or enter【用这个】】,移出【out or leave【用这个】】移动事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let oDiv = document.querySelector("div");
// 1.移入事件
// oDiv.onmouseover = function () {
// console.log("移入事件");
// }
//为了避免未知的一些BUG, 建议使用onmouseenter
// oDiv.onmouseenter = function () {
// console.log("移入事件");
// }

// 2.移出事件
// oDiv.onmouseout = function () {
// console.log("移出事件");
// }
//为了避免未知的一些BUG, 建议使用onmouseleave
// oDiv.onmouseleave = function () {
// console.log("移出事件");
// }
// 3.移动事件
oDiv.onmousemove = function () {
console.log("移动事件");
}

  • onblur和onchange区别,前者只要失去焦点就触发,后者不仅要失去焦点而且内容改变才会触发事件
  • oninput事件可以时时获取到用户修改之后的数据,只要用户修改了数据就会调用(执行), 注意点: oninput事件只有在IE9以及IE9以上的浏览器才能使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let oInput = document.querySelector("input");
// 1.监听input获取焦点
// oInput.onfocus = function () {
// console.log("获取到了焦点");
// }
// 2.监听input失去焦点
// oInput.onblur = function () {
// console.log("失去了焦点");
// }
// 3.监听input内容改变
// 注意点: onchange事件只有表单失去焦点的时候, 才能拿到修改之后的数据
// oInput.onchange = function () {
// console.log(this.value);
// }
// oninput事件可以时时获取到用户修改之后的数据, 只要用户修改了数据就会调用(执行)
// 注意点:
//oninput事件只有在IE9以及IE9以上的浏览器才能使用【低级浏览器就跳出一个框让他升级】

// 在IE9以下, 如果想时时的获取到用户修改之后的数据,
//可以通过onpropertychange事件来实现
oInput.oninput = function () {
console.log(this.value);
}

  • 一个小需求:输入框中没有内容就禁用提交按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
let oText = document.querySelector("input[type=text]");
let oSubmit = document.querySelector("input[type=submit]");
// 在JS中如果HTML标签的属性名称和取值名称一样的时候, 那么JS会返回true/false
// console.log(oSubmit.disabled);
oSubmit.disabled = true;

oText.oninput = function () {
// console.log(this.value.length);
oSubmit.disabled = this.value.length === 0;
}
// 通过代码给input设置数据
// 注意点: 如果是通过代码给input设置的数据, 那么不会触发oninput事件
oText.value = "abc";
  • oSubmit.disabled = this.value.length === 0;简洁
  • 注意点: 如果是通过代码给input设置的数据,那么不会触发oninput事件,oText.value = “abc”;