JS:鼠标事件:实现鼠标移动到div背景颜色变换,移开还原 |
您所在的位置:网站首页 › java标签背景色 › JS:鼠标事件:实现鼠标移动到div背景颜色变换,移开还原 |
前言
提示:JS onmouseover 事件 object.οnmοuseοver=function(){SomeJavaScriptCode}js学习中的误区和错误 onmouseover:鼠标移到某元素之上 onmouseout:鼠标从某元素移开
思考:为什么不能用id选择器使用第一种方法,问题出在哪里? 第一种方法:class类选择器 只能用类选择器,为什么不能用id选择器,为什么会报错οnmοuseοver=function()未定义? window.onload=function (){ let d1Obj= document.getElementsByClassName("d1")[0]; let d2Obj= document.getElementById("d2")[0]; let d3Obj= document.getElementById("d3")[0]; d1Obj.onmouseover=function(){ document.bgColor="red"; } d1Obj.onmouseout=function (){ document.bgColor="white"; } }第二种方法:id选择器 id方法:id选择器 ,使用这种形式id选择器不报错 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"; }完整代码如下: Title window.onload=function (){ let d1Obj= document.getElementsByClassName("d1")[0]; let d2Obj= document.getElementById("d2")[0]; let d3Obj= document.getElementById("d3")[0]; d1Obj.onmouseover=function(){ document.bgColor="red"; } d1Obj.onmouseout=function (){ document.bgColor="white"; } } .d1,#d2,#d3{ width: 100px; height: 50px; float: left; margin-right: 4px; } .d1{ background-color: blueviolet; } #d2{ background-color: greenyellow; } #d3{ background-color: blue; } 总结以上就是今天要讲的内容,本文仅仅简单介绍了鼠标事件的使用,js是精华,需要不断去学习和练习,下一次文章见。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |