html css 实现 白天夜晚模式 动态切换

html css 实现 白天夜晚模式 动态切换

今日,下暴雨,天黑蒙蒙的。写篇文吧。

先看效果

先来看看效果:

html css 实现 白天夜晚模式 动态切换

准备素材

准备一个白底背景图,和黑模式图,和一个中间分隔条。

白色底图:

html css 实现 白天夜晚模式 动态切换

黑色图:

html css 实现 白天夜晚模式 动态切换

分隔条:

html css 实现 白天夜晚模式 动态切换


衷心建议,如果想换成人变装模式,反差越大越精彩。

原理

一个盒子(背景图就是白色的那张),通过range类型的滑块input的拖动,来改变黑底图相对盒子的宽度width,以及分割线相对盒子最左边的距离left。

代码

// html

<div class="box">
    <span class="divider" style="left: 44%"></span>
    <input id="rangeInput" type="range" min="0" max="100" value="50" />
    <div class="blackBg" style="width: 44%"></div>
</div>
// css
.box {
    width: 782px;
    height: 452px;
    position: relative;
    top: 0;
    background-image: url('白色底图')
}

.divider {
    width: 58px;
    height: 486px;
    position: absolute;
    z-index: 2;
    background-image: url('分隔线图')
}

.blackBg {
    width: 0;
    height: 100%;
    background-image: url('黑色图'),
    background-size: 782px 452px;
    background-positon: left top;
    background-repeat: no-repeat;
}

// type='range'的input
#rangeInput {
    width: 100%;
    position: absolute;
    z-index: 3;
    top: calc(50% + 10px);
    opacity: 0;
    cursor: ew-resize;
}

js 部分

<script type="text/javascript">
function setPosition(e) {
  $(".divider").css({ left: e + "%" }), // 动 分隔条 相对盒子最左边的 距离 -> left
    $(".blackBg").css({ width: e + "%" }); // 动 黑图 的 宽度 -> width
}

$("#rangeInput").bind("input", function() {
  const e = $(this).val(); // 0 - 100
  setPosition(e);
});
</script>

好了,就这样,最后来个变身吧。下一篇。

源码地址

本文正在参加「金石计划」

原文链接:https://juejin.cn/post/7214373797692244023 作者:盏灯

(0)
上一篇 2023年3月26日 上午10:52
下一篇 2023年3月26日 下午4:00

相关推荐

发表评论

登录后才能评论