原生js实现悬浮框滑动动画

  最近在做个人博客想做个相册,鼠标悬浮后出现个div并且鼠标移动到哪个相册,div跟随到哪个相片上。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
    .imgCon {
        float: left;
    }

    img {
        display: block;
        float: left;
        margin: 0px;
        padding: 0px;
        width: 300px;
        height: 200px;
    }
    /*img:hover {
        z-index: -2;
        transform: scale(1.3);
        transition: transform 2s;
    }*/

    .upimg {
        position: relative;
        width: 300px;
        height: 200px;
        opacity: 0.6;
        background-color: black;
        /*display: none;*/
        visibility: hidden;
        transition: all 1s ease-in-out;
    }

    .hut {
        width: 600px;
        margin-left: 300px;
    }
    </style>
</head>

<body>
    <div class="hut" onmouseover="getposition()">
        <div class="imgCon">
            <img src="1.jpg" id="img1">
            <div class="upimg" id="upimg"></div>
        </div>
        <img src="1.jpg" >
        <img src="1.jpg" >
        <img src="1.jpg" >
    </div>
    <script type="text/javascript">

    function getposition() {
        var e = event || window.event;
        var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
        var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
        var x = e.pageX || e.clientX + scrollX
        var y = e.pageY || e.clientY + scrollY;
        var img = document.getElementById('img1')
        var upimg = document.getElementById('upimg')
        upimg.style.visibility = 'visible'
        upimg.style.left = `${parseInt(x / 300) * 300 - 300}px`
        upimg.style.top = `${parseInt(y / 200) * 200}px`
        return { 'x': x, 'y': y };
    }
    </script>
</body>

</html>

  上面给出了代码,首先是判断鼠标坐标xy,然后取整,设置悬浮div的坐标,然后通过设置transition来实现动画,很简单。欢迎指正

posted @ 2018-01-09 11:40  清风·流云  阅读(569)  评论(0编辑  收藏  举报