首页 > 代码库 > js图片放大

js图片放大

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>mutiplier</title>
    <style type="text/css">
        .conteainer{
            width: 800px;
            height: 900px;
            /*margin-left: 50px auto;*/
            position: relative;;
        }
        #ximg{ 
            width: 384px;
            height: 400px;
            /*margin-left: 2px;*/
            overflow: hidden;/* 超出隐藏 */
            display: none; 
            position: absolute;
         }
         #move{
             width: 80px;
             height: 70px;
             display: none;
             position: absolute;
             background-color: rgba(0,0,0,.4);
         }
    
    </style>
</head>
<body>
<div id="container">
    <img id="img" src="http://www.mamicode.com/img/campnou.jpg" width="384" height="214"> <!-- 1920 / 5 384 -->
<div id=move></div>
<div id="ximg">
    <img src="http://www.mamicode.com/img/campnou.jpg">
</div>
</div>
    <script type="text/javascript">
            //获取图片节点
            var img = document.getElementById("img");
            //获取div节点
            var ximg = document.getElementById("ximg");
            //鼠标移入事件
            var move=document.getElementById("move");
            img.onmouseover=function(){ 
                var top = this.offsetTop;//当前图片距上方的距离
                var left = this.offsetLeft+this.offsetWidth;//当前图片距左方的距离
                ximg.style.top = top+"px";
                ximg.style.left = left+"px";
                ximg.style.display = "block";//让div显示出来
                move.style.display="block"
            }
            //鼠标移动事件
            img.onmousemove = function(ent){ 
                //兼容
                var event = ent || window.event;
                //获取鼠标在图片上X轴的移动位置  水平
                // var  img_x = event.clientX-this.offsetLeft;
                // //获取鼠标在图片上Y轴的移动位置 上下
                // var  img_y = event.clientY-this.offsetTop;
                var  img_x = event.clientX;
                //获取鼠标在图片上Y轴的移动位置 上下
                var  img_y = event.clientY;

                if(img_x>(384-40))
                    img_x=384-40;
                if(img_x<40)
                    img_x=40;
                if(img_y>(214-35))
                    img_y=214-35;
                move.style.left=img_x-40+"px";
                ximg.scrollLeft = (img_x-48)*5;
                move.style.top=img_y-35+"px";
                ximg.scrollTop = (img_y-50)*5;
                
            }
            //移出事件
            img.onmouseout=function(){ 
                ximg.style.display="none";
                move.style.display="none";
            }
    </script>
</body>
</html>

技术分享

 

js图片放大