使用jQuery的事件对象实现图片跟随鼠标移动的效果

运行结果如下:

 随着鼠标进入小图移动,大图会出现并随着鼠标的移动而移动。

代码如下:

<html>

    <head>

        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

        <script type="text/javascript">

            $(function(){

                //小图分别绑定鼠标移入、鼠标移出和鼠标移动事件

                $("#small").bind("mouseover mouseout mousemove",function(event){

                    if(event.type=="mouseover"){

                        $("#showBig").show();

                    }else if(event.type=="mouseout"){

                        $("#showBig").hide();

                    }else if(event.type=="mousemove"){

                        //鼠标移动时会进入大图  绑定在小图上面的事件就

                        //起不了作用  因此在获取的值上加10

                        $("#showBig").offset({

                            //获取到鼠标的坐标

                            left: event.pageX+10,

                            top:  event.pageY+10

                        });

                    }

                })

            })

        </script>

        <style type="text/css">

            body{text-align: center;}

            #small{margin-top: 150px;}

            #showBig{

                position: absolute;

                display: none;

                }

        </style>

    </head>

    <body>

        <img id="small" src="1.jpg" width="300px">

        <div id="showBig">

            <img src="1.jpg" width="450px"/>

        </div>

    </body>

</html>

猜你喜欢

转载自blog.csdn.net/defined_/article/details/118960822