<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
width: 300px;
height: 300px;
border: 1px solid black;
position: absolute;
left: 30px;
top: 30px;
}
.box1 img {
width: 100%;
height: 100%;
}
.box2 {
width: 600px;
height: 600px;
border: 1px solid black;
position: absolute;
left: 500px;
top: 30px;
}
.box2 img {
width: 100%;
height: 100%;
}
.mengceng {
display: none;
width: 70px;
height: 70px;
background-color: black;
position: absolute;
top: 0;
left: 0;
opacity: 0.5;
}
</style>
<script>
window.onload = function () {
var BOX1 = document.getElementById("box1");
var BOX2 = document.getElementById("box2");
var QMengceng = document.getElementById("mengceng");
QMengceng.onmouseover = function () {
QMengceng.style.display = "block";
}
QMengceng.onmouseout = function () {
QMengceng.style.display = "none";
}
}
</script>
</head>
<body>
<div class="box1">
<img src="../图片的使用/放大镜图片.jfif" alt="">
<div class="mengceng"></div>
</div>
<div class="box2">
<img src="../图片的使用/放大镜图片.jfif" alt="">
</div>
</body>
</html>
我只是想给左边的图片设置一个鼠标移动上去就显示蒙层,移出就不显示,但是F12调试台为什么会显示
Uncaught TypeError: Cannot set property 'onmouseover' of null
at window.onload
而且功能也无法实现
首先document.getElementById()取的是id名,而不是class名
而且我觉得你思路不对,你在img下面加个div来显示蒙层?那么就算你代码运行成功,蒙层是显示在img下面,你应该用考虑用伪类选择器或者伪元素选择器。
我是直接改变div的class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1 {
width: 300px;
height: 300px;
border: 1px solid black;
position: absolute;
left: 30px;
top: 30px;
}
#box1 img {
width: 100%;
height: 100%;
}
#box2 {
width: 600px;
height: 600px;
border: 1px solid black;
position: absolute;
left: 500px;
top: 30px;
}
#box2 img {
width: 100%;
height: 100%;
}
.mengceng {
width: 70px;
height: 70px;
background-color: black;
position: absolute;
top: 0;
left: 0;
opacity: 0.5;
}
</style>
<script>
window.onload = function () {
var BOX1 = document.getElementById("box1");
var BOX2 = document.getElementById("box2");
var QMengceng = document.getElementById("mengceng");
BOX1.onmouseover = function () {
BOX1.className = 'mengceng';
}
BOX1.onmouseout = function () {
BOX1.className = "";
}
};
</script>
</head>
<body>
<div id="box1">
<img src="images/ss.jpg" alt="">
</div>
<div id="box2">
<img src="images/ss.jpg" alt="">
</div>
</body>
</html>
你没有mengceng这个对象,并且box1,box2是样式,并不是id,要给控件加上id
而且就算有mengceng这个对象,默认display为none也不会触发绑定的事件,先整清楚dom结构先吧