JS:鼠标事件:实现鼠标移动到div背景颜色变换,移开还原

it2025-08-10  9

前言

提示:JS

onmouseover 事件

object.οnmοuseοver=function(){SomeJavaScriptCode}

js学习中的误区和错误

onmouseover:鼠标移到某元素之上 onmouseout:鼠标从某元素移开

 

思考:为什么不能用id选择器使用第一种方法,问题出在哪里?

第一种方法:class类选择器     只能用类选择器,为什么不能用id选择器,为什么会报错οnmοuseοver=function()未定义?

<script type="text/javascript"> window.onload=function (){ let d1Obj= document.getElementsByClassName("d1")[0];<!--class方法正确 id选择器报错:未定义--> let d2Obj= document.getElementById("d2")[0]; let d3Obj= document.getElementById("d3")[0]; d1Obj.onmouseover=function(){ document.bgColor="red"; } d1Obj.onmouseout=function (){ document.bgColor="white"; } } </script>

第二种方法:id选择器

id方法:id选择器 ,使用这种形式id选择器不报错

<script type="text/javascript"> function over(){ var x = document.getElementById("d1").innerHTML="鼠标不在上面的颜色"; var x = document.getElementById("d1").style.color="pick"; var x = document.getElementById("d1").style.backgroundColor="dodgerblue"; } function out(){ var x = document.getElementById("d1").innerHTML="鼠标在上面的颜色"; var x = document.getElementById("d1").style.color="red"; var x = document.getElementById("d1").style.backgroundColor="green"; } </script>

完整代码如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> window.onload=function (){ let d1Obj= document.getElementsByClassName("d1")[0];<!--class方法 id选择器报错:未定义--> let d2Obj= document.getElementById("d2")[0]; let d3Obj= document.getElementById("d3")[0]; d1Obj.onmouseover=function(){ document.bgColor="red"; } d1Obj.onmouseout=function (){ document.bgColor="white"; } } </script> <!--<script type="text/javascript"> function over(){ id方法 var x = document.getElementById("d1").innerHTML="鼠标不在上面的颜色"; var x = document.getElementById("d1").style.color="pick"; var x = document.getElementById("d1").style.backgroundColor="dodgerblue"; } function out(){ var x = document.getElementById("d1").innerHTML="鼠标在上面的颜色"; var x = document.getElementById("d1").style.color="red"; var x = document.getElementById("d1").style.backgroundColor="green"; } </script>--> <style type="text/css"> .d1,#d2,#d3{ width: 100px; height: 50px; float: left; margin-right: 4px; } .d1{ background-color: blueviolet; } #d2{ background-color: greenyellow; } #d3{ background-color: blue; } </style> </head> <body> <!--<div id="d1" onmouseover = "over()" onmouseout="out()"></div>--> <div class="d1"></div> <div id="d2"></div> <div id="d3"></div> </body> </html>

总结

以上就是今天要讲的内容,本文仅仅简单介绍了鼠标事件的使用,js是精华,需要不断去学习和练习,下一次文章见。

最新回复(0)