JavaScript事件类型和事件处理程序

● 之前我们用过了很多此的点击事件,这次让我们来学习另一种事件类型

mouseenter

"mouseenter" 是一个鼠标事件类型,它在鼠标指针进入指定元素时触发。

javascript 复制代码
const h1 = document.querySelector('h1');
h1.addEventListener('mouseenter', function (e) {
  alert('你正在查看H1标题的内容');
});

当鼠标放上去的时候就会触发弹窗;

● 除了上面的写法,我们还有另一种写法

javascript 复制代码
const h1 = document.querySelector('h1');
h1.onmouseenter = function (e) {
  alert('你正在查看H1标题的内容');
};

● 这个和上面实现效果一样,这个会反复的出发,你每次鼠标移动至H1就会触发,我们也可以只让它使用一次;

javascript 复制代码
const h1 = document.querySelector('h1');
const alertH1 = function (e) {
  alert('你正在查看H1标题的内容');
  h1.removeEventListener('mouseenter', alertH1);
};
h1.addEventListener('mouseenter', alertH1);

● 当然,我们也可以添加一个定时器来操作删除事件

javascript 复制代码
const h1 = document.querySelector('h1');
const alertH1 = function (e) {
  alert('你正在查看H1标题的内容');
};
h1.addEventListener('mouseenter', alertH1);

setTimeout(() => h1.removeEventListener('mouseenter', alertH1), 3000);

● 我们还可以直接再HTML元素中添加事件,当然这再实际的生产中并不常见

javascript 复制代码
<div class="header__title">
            <h1 onmouseenter="alert('我是H1标题')">
          When
          <!-- Green highlight effect -->
          <span class="highlight">banking</span>
          meets<br />
          <span class="highlight">minimalist</span>
        </h1>
            </div>
相关推荐
前端怎么个事2 分钟前
框架的源码理解——V3中的ref和reactive
前端·javascript·vue.js
Fu_lucas5 分钟前
Python Logging 模块完全指南
开发语言·python
Eiceblue7 分钟前
Python 在Excel单元格中应用多种字体样式
开发语言·vscode·python·pycharm·excel
不爱吃饭爱吃菜1 小时前
uniapp微信小程序一键授权登录
前端·javascript·vue.js·微信小程序·uni-app
heart000_11 小时前
从零开始打造个人主页:HTML/CSS/JS实战教程
javascript·css·html
90后小陈老师2 小时前
3D个人简历网站 5.天空、鸟、飞机
前端·javascript·3d
chenbin___2 小时前
react native text 显示 三行 超出部分 中间使用省略号
javascript·react native·react.js
shykevin5 小时前
python开发Streamable HTTP MCP应用
开发语言·网络·python·网络协议·http
我不是程序猿儿5 小时前
【C#】 lock 关键字
java·开发语言·c#
漫路在线6 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python