利用offsetTop实现移入移出上下出现阴影

代码如下

<!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>
        div {
            position: absolute;
            left: 0;
            top: 0;
        }
        
        .box1 {
            width: 400px;
            height: 400px;
            background-color: red;
            overflow: hidden;
        }
        
        .box2 {
            width: 200px;
            height: 200px;
            background-color: #000;
            opacity: 0.5;
            top: -200px;
        }
        
        .box3 {
            width: 200px;
            height: 200px;
            background-color: #000;
            opacity: 0.5;
            top: 400px;
        }
    </style>
</head>

<body>
    <div class="box1">
        <div class="box2"></div>
        <div class="box3"></div>
    </div>

</body>
<script>
    var box1 = document.querySelector('.box1');
    var box2 = document.querySelector('.box2');
    var box3 = document.querySelector('.box3');
    var dsq_1; //全局变量
    var dsq1_1 //全局变量

    console.log(box2.offsetTop);
    box1.onmouseover = function() {
        clearInterval(dsq1_1); //先清除dsq1_1定时器,避免受影响
        dsq();
    }
    box1.onmouseout = function() {
        clearInterval(dsq_1);
        dsq1();
    }

    function dsq() {

        dsq_1 = setInterval(function() {
            //判断当前box2的top值是否大于等于0或当前box3的top值是否小于等于200
            // box2最初的top为-200px,box3最初的top为400px
            if (box2.offsetTop >= 0 || box3.offsetTop <= 200) {
                clearInterval(dsq_1); //清除定时器
            } else {
                box2.style.top = box2.offsetTop + 1 + 'px'; //阴影从上往下出现
                box3.style.top = box3.offsetTop - 1 + 'px'; //阴影从下往上出现
            }

        }, 1)
    }

    function dsq1() {

        dsq1_1 = setInterval(function() {
            if (box2.offsetTop <= -200 || box3.offsetTop >= 400) {
                clearInterval(dsq_1);
            } else {
                box2.style.top = box2.offsetTop - 1 + 'px'; //阴影从下往上消失
                box3.style.top = box3.offsetTop + 1 + 'px'; //阴影从上往下消失
            }

        }, 1)
    }
</script>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值