要求:
- 鼠标移入美女图片,出现半透明正方块
- 鼠标移出美女图片,隐藏半透明正方块
- 鼠标在美女图片区域移动,半透明正方块随着移动
- 半透明正方块移动到美女图片四边界时,停止移动
- 点击下面小图切换大图
html结构部分
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<link rel="stylesheet" href="./css/fdj.css">
</head>
<body>
<!-- 包裹整个项目的大盒子 -->
<div class="container">
<!-- 放大镜显示的效果 -->
<div class="bigImg">
<p></p>
</div>
<!-- 点击显示按钮ul -->
<ul>
<li><img src="./images/show_1.jpg" alt=""></li>
<li><img src="./images/show_2.jpg" alt=""></li>
<li><img src="./images/show_3.jpg" alt=""></li>
<li><img src="./images/show_4.jpg" alt=""></li>
</ul>
</div>
<script src="./js/img.js"></script>
</body>
</html>
css样式
* {
margin: 0;
padding: 0;
}
.big {
width: 300px;
height: 300px;
background-color: skyblue;
position: relative;
background: url(../images/show_1.jpg);
/* background */
}
.small {
width: 100px;
height: 100px;
position: absolute;
background-color: yellow;
opacity:0.5;
left: 0px;
top: 0px;
/* 当前元素事件不起作用 */
pointer-events: none;
display: none;
}
.container{
width: 500px;
height: 500px;
/* background-color: pink; */
}
ul{
list-style: none;
}
ul li{
width: 50px;
height: 50px;
background-color: red;
margin-left: 20px;
float: left;
}
ul li img{
width: 50px;
}
js代码部分
var divEle = document.querySelector('.bigImg')
divEle.classList.add('big')
var pEle = document.querySelector('p')
pEle.classList.add('small')
//给ulEle添加一个点击事件
var ulEle = document.querySelector('ul')
ulEle.addEventListener('click',function(e){
e = e || window.event
let target = e.target || e.srcElement
//获取到事件委托的图片地址
let url = target.getAttribute('src')
divEle.style.background = `url(${url})`
})
//给大盒子绑定鼠标移动事件、返回移动值
divEle.onmousemove = function (e) {
e = e || window.event //事件对象
console.log('X ', e.offsetX, ' Y :', e.offsetY);
//将现在的鼠标在的x,y值传给小盒子,并让鼠标永远在小盒子中间
var bigPosX = e.offsetX - pEle.clientWidth / 2
var bigPosY = e.offsetY - pEle.clientHeight / 2
// 小盒子的边界问题
//右边界临界值 = 大盒子的宽度 - 小盒子的宽度
var maxRight = divEle.clientWidth - pEle.clientWidth
//下边界临界值 = 大盒子的高度 - 小盒子的高度
var maxBottom = divEle.clientHeight - pEle.clientHeight
// 左边界
if (bigPosX < 0) {
bigPosX = 0
}
//右边界值
if (bigPosX > maxRight) {
bigPosX = maxRight
}
//上边界值
if (bigPosY < 0) {
bigPosY = 0
}
//下边界值
if (bigPosY > maxBottom) {
bigPosY = maxBottom
}
//将值赋值给小盒子的position的left和top属性中去
pEle.style.left = bigPosX + 'px' //将鼠标X轴的位置传给小盒子的position
pEle.style.top = bigPosY + 'px' //将鼠标y轴的位置传给小盒子的position
}
//小盒子隐藏显示: 摸到大盒子显示小盒子
divEle.onmouseover = function(){
pEle.style.display = 'block'
}
divEle.onmouseout = function(){
pEle.style.display = 'none'
}