12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <!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;
- }
- #container{
- position: relative;
- }
- #smallBox{
- width: 400px;
- height: 400px;
- }
- #bigBox{
- width: 800px;
- height: 800px;
- left: 400px;
- top: 0;
- position: absolute;
- }
- #drag{
- width: 200px;
- height: 200px;
- background: rgba(0,0,0,0.3);
- position: absolute;
- left: 0;
- top: 0;
- display: none;
- }
- </style>
- </head>
- <body>
- <div id="container">
- <div id="smallBox">
- <img src="images/1.jpg" alt="">
- <div id="drag"></div>
- </div>
- <div id="bigBox">
- <img src="images/2.jpg" alt="">
- </div>
- </div>
- <script>
- var small = document.getElementById('smallBox')
- var drag = document.getElementById('drag')
-
- //鼠标划入显示遮罩层
- small.onmouseover = function(){
- drag.style.display = 'block'
- }
- //鼠标划出显示遮罩层
- small.onmouseout = function(){
- drag.style.display = 'none'
- }
- //鼠标滑动
- small.onmousemove = function(e){
- var xLeft = e.clientX - drag.offsetWidth / 2
- var xTop = e.clientY - drag.offsetHeight /2
- drag.style.left = xLeft + 'px'
- drag.style.top = xTop + 'px'
- if(drag.offsetLeft <= 0){
- drag.style.left = 0
- }
- if(drag.offsetTop <= 0 ){
- drag.style.top = 0
- }
- //横轴最大移动距离
- var zLeft = small.offsetWidth - drag.offsetWidth
- //纵轴最大移动距离
- var zTop = small.offsetHeight - drag.offsetHeight
- if(drag.offsetLeft > zLeft){
- drag.style.left = zLeft + 'px'
- }
- if(drag.offsetTop > zTop){
- drag.style.top = zTop + 'px'
- }
- }
- </script>
- </body>
- </html>
|