最近,在书写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、问题测试效果
鼠标移上去
移开后
鼠标点击