小例子:

京东购物车

京东购物车效果:

前端JavaScript(3)-关于DOM操作的相关案例,JS中的面向对象、定时器、BOM、位置信息

实现原理:

前端JavaScript(3)-关于DOM操作的相关案例,JS中的面向对象、定时器、BOM、位置信息

 

用2个盒子,就可以完整效果。

先让上面的小盒子向下移动1px,此时就出现了压盖效果。小盒子设置z-index压盖大盒子,将小盒子的下边框去掉,就可以实现效果。

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        /*背景盒子*/
        .box{
            width: 500px;
            height: 110px;
            margin: 100px auto;
            background-color: rgba(0,0,0,0.2);
            /*相对定位*/
            position: relative;
        }
        /*购物车*/
        .car{
            width: 150px;
            height: 30px;
            background-color: #fff;
            /*设置绝对定位,参考对象为box*/
            position: absolute;
            left: 200px;
            /*这里必须是3.1,如果是3,放大时,会看到细线*/
            top: 3.1px;
            /*设置元素的堆叠顺序*/
            z-index: 9;
            border: 1px solid green;
        }
        .shop{
            width: 310px;
            height: 70px;
            background-color: #fff;
            position: absolute;
            top:33px;
            left: 40px;
            border: 1px solid green;
            /*隐藏不显示*/
            display: none;
        }
        /*去掉底部的边框*/
        div.c{
            border-bottom-width: 0;
        }
        /*设置盒子边框*/
        div.t{
            border:  1px solid green;
        }

    </style>
</head>
<body>
<div class="box">
    <div class="car" >我的购物车</div>
    <div class="shop t" ></div>
</div>

<script type="text/javascript">
    var myCar = document.getElementById('myCar');  //小盒子
    var shop = document.getElementById('shop');  //大盒子

    //onmouseenter 事件在鼠标指针移动到元素上时触发
    myCar.onmouseenter = function(){
        shop.style.display = 'block';  //此元素将显示为块级元素
        myCar.className += ' c';  //去掉底部的边框
    }
    // onmouseleave 事件在鼠标移除元素时触发
    myCar.onmouseleave = function(){
        //大盒子隐藏
        shop.style.display = 'none'; //此元素不会被显示

        myCar.removeAttribute('class');  //删除class属性,此时有2个class,分别是car和c。都会被删除
        myCar.className = 'car';  //重新设置class为car,让它显示默认样式。
    }

</script>

</body>
</html>
View Code

相关文章:

  • 2021-06-10
  • 2021-04-09
  • 2022-01-21
  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案