通过页面滚动实现图片透明度变化(html+css+js)

效果图

GIF 2021-12-11 16-47-04.gif

代码

html

    <section class="banner">
        <!-- 叠在图片上的盒子 -->
        <div class="cover"></div>
        <!-- 图片中要填充的内容 -->
        <div>3224224</div>
    </section>
复制代码

section 换为 div 也行,这里只是个人的一个尝试。
<section> 标签定义文档中的节(section、区段)。比如章节、页眉、页脚或文档中的其他部分。

css

/* 父 */
.banner {
    position: relative;
    height: 600px;
    background-image: url(./image/home.jpg);
    background-size: cover;
    display: flex;
    z-index: 1;
}
/* 子 */
.cover {
    height: 600px;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: black;
    opacity: 0;
    filter:alpha(opacity:0);
    z-index: 10;
}
复制代码

子绝父相,z-index 为层叠优先级,大的叠在上层

javascript

// 获取元素
var img = document.querySelector(".banner");
var imgCover = document.querySelector(".cover")

// 页面滚动事件
document.addEventListener('scroll', function () {
    // window.pageYOffset 页面被卷去的头部
    if (window.pageYOffset > 400) { // 400 为页面滚到的位置,可自定义
        startchange(100, imgCover);
    } else {
        startchange(0, imgCover);
    }
    // console.log(i++);
})

var alpha = 0;   // 透明度 (要赋值,值随意)
// value: 变化后的透明度, div: 将变化的元素
function startchange(value, div) {
    clearInterval(timer);

    // speed: 变化速度
    var speed = 0;

    // 当所需透明度大于当前透明度时
    if (value > alpha) {
        speed = 5;

        // 当所需透明度小于当前透明度时
    } else if (value < alpha) {
        speed = -5;
    }

    // 定时器
    var timer = setInterval(function () {

        // 若透明度达到要求
        if (value == alpha) {
            // 清空已有定时器
            clearInterval(timer);
        } else {
            // 透明度调节
            alpha += speed;
            //IE 兼容
            div.style.filter = 'alpha(opacity:' + alpha + ')';
            //火狐...
            div.style.opacity = alpha / 100;
            if (alpha == value) {
                alpha = value;
            }
        }
    }, 40)// 每40毫秒触发一次定时器事件,自行根据需求调节
}
复制代码

其他

一开始没有使用父子盒子,而是尝试了伪类 :after
:after 选择器: 在被选元素的内容后面插入内容。 必须含有 content 属性来指定要插入的内容。

/* .banner:after {
    content: attr(data-attr);  
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: black;
    opacity: 0.6;
} */
复制代码

attr() 函数返回所选元素的属性值。
data-* 属性用于存储页面或应用程序的私有自定义数据(HTML5)
参考:js 更改伪类样式

例:在每个链接后的括号中插入 href 属性的值

a:after {
  content: " (" attr(href) ")";
}
复制代码

后面了解到使用 js 去动态更改伪类样式较为麻烦,转而用开头的父子层叠的方法。

猜你喜欢

转载自juejin.im/post/7040392014273183757