当前位置: 首页 > news >正文

html基于onmouse事件让元素变颜色

最近,在书写div块时,遇到一个小问题,这个小问题我搞了将近一个小时多才慢慢解决。问题是这样子的,有一个div块,我想让鼠标移上去变成蓝色,移开变成灰色,当鼠标按下去时让他变成深蓝色。于是就单纯添加onmouse事件,实验起来发现,笔者鼠标按下去确实变色,但是移开时却又变回来。于是为了此问题写了这篇博文

1、问题起源

div变颜色不如笔者想法,移上去变色,移开变色,按下去变色但不想让按下去再移开变色。

2、问题解决方案

设计onmouse事件,温习下onmouse事件

  • onmousedown 事件会在鼠标被按下时发生
  • onmouseup:事件会在用户鼠标时按键被松开时执行
  • onmousemove:事件会在鼠标移动到指定元素后执行
  • onmouseout:事件会在鼠标移出指定的元素对象时执行
<!DOCTYPE html>
<html><head><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"><meta charset="utf-8"><title></title><style>#mTestCases{width:100px;height:100px;background-color: grey;}#mAuto_Test {width:100px;height:100px;margin-top:5px;background-color: grey;}</style></head><body><div id="mTestCases"></div><div id="mAuto_Test"></div><script>var tmp1 = document.getElementById("mTestCases");tmp1.onmousedown = function(){this.style.backgroundColor = "rgb(72,152,246)";this.style.color = "white";this.onmouseout = null;var tp2 = document.getElementById("mAuto_Test");tp2.onmouseout = function(){this.style.backgroundColor='rgb(249,250,255)';this.style.color='rgb(94,104,134)';}tp2.style.backgroundColor = "rgb(249,250,255)";tp2.style.color = "rgb(94,104,134)";}tmp1.onmousemove = function(){this.style.backgroundColor = "rgb(72,152,246)";this.style.color = "white";}var tmp2 = document.getElementById("mAuto_Test");tmp2.onmousedown = function(){this.style.backgroundColor = "rgb(72,152,246)";this.style.color = "white";this.onmouseout = null;var tp2 = document.getElementById("mTestCases");tp2.onmouseout = function(){this.style.backgroundColor='rgb(249,250,255)';this.style.color='rgb(94,104,134)';}tp2.style.backgroundColor = "rgb(249,250,255)";tp2.style.color = "rgb(94,104,134)";}tmp2.onmousemove = function(){this.style.backgroundColor = "rgb(72,152,246)";this.style.color = "white";}</script></body></html>

3、问题测试效果

鼠标移上去
在这里插入图片描述
移开后

在这里插入图片描述

鼠标点击
在这里插入图片描述

http://www.lryc.cn/news/95361.html

相关文章:

  • Linux环境PostgreSQL安装
  • Rust 数据类型 之 结构体(Struct)
  • 数据结构之Queue的实现
  • rust声明式宏
  • 第二章:Learning Deep Features for Discriminative Localization ——学习用于判别定位的深度特征
  • 【CSS】box-shadow 属性
  • 基于深度学习的高精度课堂人脸检测系统(PyTorch+Pyside6+YOLOv5模型)
  • Mysql错误日志、通用查询日志、二进制日志和慢日志的介绍和查看
  • 【Linux】Tcp服务器的三种与客户端通信方法及守护进程化
  • 【Spring Cloud】git 仓库新的配置是如何刷新到各个微服务的原理步骤
  • 三,创建订单微服务消费者 第三章
  • 【雕爷学编程】Arduino动手做(87)---ULN2003步进电机模组2
  • 【C#】微软的Roslyn 是个啥?
  • 两个小封装电机驱动芯片:MLX813XX、A4950
  • 数据结构【绪论】
  • 掌握无人机遥感数据预处理的全链条理论与实践流程、典型农林植被性状的估算理论与实践方法、利用MATLAB进行编程实践(脚本与GUI开发)以及期刊论文插图制作等
  • Angular中组件设计需要注意什么?
  • 电容触摸屏(TP)的工艺结构
  • Qt小妙招:如何在可执行文件生成后,在pro文件中添加其他命令操作?
  • 做好防雷检测的意义和作用
  • 计算机启动过程uefi+gpt方式
  • 探索容器镜像安全管理之道
  • 【MySQL】内置函数
  • 使用arm-none-eabi-gcc编译器搭建STM32的Vscode开发环境
  • 图数据库Neo4j学习二——cypher基本语法
  • ChatGPT:人工智能交互的未来之光
  • 128最长连续数组
  • redis 1
  • vue+Element项目中v-for循环+表单验证
  • Day 66-68 主动学习之ALEC