html css 实现图片扫描特效

发布时间 2023-05-17 11:49:13作者: jsper

 

实现这个特效需要做3个层,所以要用到CSS绝对定位和层级z-index以及设置top、left、bottom、right的值。
大体结构是一个容器,容器里放3个层,底层是4个角的边框效果容器,中间层是要扫描的图片容器,顶层是扫描线容器,这3个层通过z-index来实现层级,它们的高宽度都取父容器的高宽度inherit。
由于图片尺寸可能不同,所以<img>标签的样式设置了object-fit: contain;这样始终能显示图片所有内容并自动按高宽度充满父容器。
扫描效果通过动画实现,定义动画为4秒,并且循环。一次循环扫描线从顶部移动到底部,再从底部移回顶部。

版本一:

<!DOCTYPE html>
<html>
    <head>
        <mate charset="UTF-8"/>
        <title>扫描特效</title>
        <style type="text/css">
            @keyframes scan {
                0% {
                    margin-top: 0px;
                }
                50% {
                    margin-top: 300px;
                }
                100% {
                    margin-top: 0px;
                }
            }
        </style>
    </head>    
    <body>
        <h1>扫描动画</h1>
        <h3>https://www.cnblogs.com/jsper</h3>
        <div style="display:flex;">
            <div style="width:100px;height:100px;background-color: yellow;margin:20px;">网页其他元素块</div>
            <!-- 扫描特效组件 -->
            <div style="width:400px;height:300px;border:1px solid green;">
                <div style="position:absolute;z-index:0;width:inherit;height:inherit;">
                    <div style="position:absolute;width:100px;height:100px;background-color:green;top:-4px;left:-4px;"></div>
                    <div style="position:absolute;width:100px;height:100px;background-color:green;top:-4px;right:-4px;"></div>
                    <div style="position:absolute;width:100px;height:100px;background-color:green;bottom:-4px;left:-4px;"></div>
                    <div style="position:absolute;width:100px;height:100px;background-color:green;bottom:-4px;right:-4px;"></div>
                </div>
                <div style="position:absolute;z-index:10;width:inherit;height:inherit;background-color:white;">
                    <img src="dianzifapiao.png" style="width:inherit;height:inherit;object-fit: contain;"/>
                </div>
                <div style="position:absolute;z-index:20;width:inherit;height:2px;background:greenyellow;box-shadow: 0 0 10px 3px green;animation: scan 4s ease-in-out infinite;"></div>
            </div>
            <div style="width:100px;height:100px;background-color: yellow;margin:20px;">网页其他元素块</div>
        </div>
    </body>
</html>