学堂 学堂 学堂公众号手机端

HTML鼠标悬停

lewis 3年前 (2022-10-10) 阅读数 4 #技术

HTML鼠标悬停

简介

HTML鼠标悬停是指在网页中,当鼠标指针悬停在某一元素上时,触发某种效果或行为,常见的鼠标悬停效果包括改变元素的颜色、显示隐藏的内容等,在HTML中,我们可以通过CSS和JavaScript来实现鼠标悬停效果。


CSS实现鼠标悬停

方法一:使用伪类选择器

1、使用:hover伪类选择器,为元素添加鼠标悬停样式。

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
    width: 100px;
    height: 100px;
    backgroundcolor: red;
  }
  .box:hover {
    backgroundcolor: blue;
  }
</style>
</head>
<body>
  <div class="box"></div>
</body>
</html>

方法二:使用mouseovermouseout事件

1、为元素添加mouseovermouseout事件监听器,分别设置元素的样式。

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
    width: 100px;
    height: 100px;
    backgroundcolor: red;
  }
</style>
<script>
  function mouseOver() {
    this.style.backgroundColor = 'blue';
  }
  function mouseOut() {
    this.style.backgroundColor = 'red';
  }
</script>
</head>
<body>
  <div class="box" onmouseover="mouseOver()" onmouseout="mouseOut()"></div>
</body>
</html>

JavaScript实现鼠标悬停

方法一:使用addEventListener

1、为元素添加mouseentermouseleave事件监听器,分别设置元素的样式。

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
    width: 100px;
    height: 100px;
    backgroundcolor: red;
  }
</style>
<script>
  const box = document.querySelector('.box');
  box.addEventListener('mouseenter', () => {
    box.style.backgroundColor = 'blue';
  });
  box.addEventListener('mouseleave', () => {
    box.style.backgroundColor = 'red';
  });
</script>
</head>
<body>
  <div class="box"></div>
</body>
</html>

方法二:使用onmouseenteronmouseleave属性

1、为元素添加onmouseenteronmouseleave属性,分别设置元素的样式。

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
    width: 100px;
    height: 100px;
    backgroundcolor: red;
  }
</style>
<script>
  function mouseEnter() {
    this.style.backgroundColor = 'blue';
  }
  function mouseLeave() {
    this.style.backgroundColor = 'red';
  }
</script>
</head>
<body>
  <div class="box" onmouseenter="mouseEnter()" onmouseleave="mouseLeave()"></div>
</body>
</html>
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门