这次实现的效果如下:
这次的案例稍微有一点难度,在css和js上都需要多加思考,话不多说,让我们来开始吧~
position:absolute
,然后设置left
和top
的值来使其相邻。
小盒子S我们同样可以为其设置position:absolute
,调整一下背景颜色即可。onmousemove
函数,传入参数client,表示时间鼠标在盒子A上移动。我们通过client获取鼠标的位置(clientX,clientY),然后通过(clientX-boxA.offsetLeft,clientY-boxA.offsetTop)
可获得鼠标在图像上的相对坐标,通过此值减去盒子S的宽度、高度的一半即可获得盒子S在A中的位置。
==但是要注意==,记得为盒子S设置边界,当横坐标为0或为A盒子宽度、纵坐标为0或者A盒子高度时,要使其坐标固定。background-position
为y,达到放大+移动的效果。可能我的实现方法过程比较复杂,大家如果想到更好的方法可以留言呀
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
position: absolute;
left: 180px;
top: 100px;
}
#box img {
width: 400px;
height: 300px;
border: 1px solid rgba(255, 255, 255, 0.7);
vertical-align: bottom;
}
#nav {
width: 480px;
height: 360px;
border: 1px solid rgba(255, 255, 255, 0.7);
position: absolute;
left: 582px;
top: 100px;
background-image: url(../img/morn.jpg);
background-repeat: no-repeat;
background-size: 250% 250%
}
#small {
width: 160px;
height: 120px;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
<div id="small"></div>
<img src="../img/morn.jpg" alt="">
</div>
<div id="nav"></div>
<script>
let box = document.getElementById("box");
let small = document.getElementById("small");
let nav = document.getElementById("nav");
box.onmousemove = function (client) {
let x = client.clientX - box.offsetLeft;
let y = client.clientY - box.offsetTop;
small.style.left = x - 80 + 'px';
small.style.top = y - 60 + 'px';
let dis_x = box.offsetLeft + box.offsetWidth - client.clientX;
let dis_y = box.offsetTop + box.offsetHeight - client.clientY;
nav.style.backgroundPositionX = (80 - x) * 3 + 'px';
nav.style.backgroundPositionY = (60 - y) * 3 + 'px';
if (x - 80 < 0) {
small.style.left = 0;
nav.style.backgroundPositionX = 0;
}
if (dis_x <= 80) {
small.style.left = box.offsetWidth - 160 + 'px';
nav.style.backgroundPositionX = (160 - box.offsetWidth) * 3 + 'px';
}
if (y - 60 < 0) {
small.style.top = 0;
nav.style.backgroundPositionY = 0;
}
if (dis_y < 60) {
small.style.top = box.offsetHeight - 120 + 'px';
nav.style.backgroundPositionY = (120 - box.offsetHeight) * 3 + 'px';
}
small.style.backgroundColor = "rgba(135, 207, 235, 0.61)";
}
box.onmouseout = function () {
small.style.backgroundColor="transparent"
}
</script>
</body>
</html>