HTML5+CSS3+JS小实例:马赛克背景的按钮特效

实例:马赛克背景的按钮特效
开发工具:HTML+CSS+JS
效果:

源码:
【html】【js】

<!DOCTYPE html>
<html>
 
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
 
    <title>马赛克背景的按钮特效</title>
    <link rel="stylesheet" href="../css/83.css">
</head>
 
<body>
    <div class="button">
        <div class="back" style="--c:#e74c3c;"></div>
        <p>求点赞</p>
    </div>
    <div class="button">
        <div class="back" style="--c:#2ecc71;"></div>
        <p>求关注</p>
    </div>
    <div class="button">
        <div class="back" style="--c:#3498db;"></div>
        <p>求收藏</p>
    </div>
    <div class="button">
        <div class="back" style="--c:#9b59b6;"></div>
        <p>求转发</p>
    </div>
    <script>
        // 获取所有的.back层
        var backs=document.getElementsByClassName('back');
        // 遍历所有的.back层,并添加span元素作为背景
        for(let i=0;i<backs.length;i++){
            // 当前.back层
            let back=backs[i];
            // 宽高尺寸采用.back层的1/25宽度
            let width=back.clientWidth/25;
            let height=width;
            // 计算所需的背景块数量
            let count=25*parseInt(back.clientHeight/height);
            for(let j=0;j<count;j++){
                // 根据计算结果添加对应数量的span元素
                let span=document.createElement('span');
                span.style.width=width+'px';
                span.style.height=width+'px';
                // 设置动画过渡:时长 线性 动画延迟
                span.style.transition='0.2s linear '+Math.random()/2+'s';
                back.appendChild(span);
            }
        }
    </script>
</body>
 
</html>

【css】

*{
    /* 初始化 */
    margin: 0;
    padding: 0;
}
body{
    /* 100%窗口高度 */
    height: 100vh;
    /* 弹性布局 水平+垂直居中 */
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: linear-gradient(200deg,#485563,#29323c);
}
.button{
    width: 250px;
    height: 80px;
    border: 2px solid #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10px;
    /* 溢出隐藏 */
    overflow: hidden;
    margin: 15px 0;
    cursor: pointer;
    /* 相对定位 */
    position: relative;
}
.button p{
    font-size: 22px;
    font-weight: bold;
    /* 动画过渡 */
    transition: 1s;
    /* 绝对定位 */
    position: absolute;
}
.button .back{
    width: 100%;
    height: 100%;
    position: absolute;
}
.button .back span{
    background-color: #fff;
    display: block;
    float: left;
}
.button:hover div span{
    /* 通过var函数调用自定义属性--c,设置背景颜色 */
    background-color: var(--c);
}
.button:hover p{
    color: #fff;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容