3、图片+动态样式

知识点:

效果

在这里插入图片描述

JS 实时更新 CSS 值

  1. 获取页面中 input 元素

  2. 给每个 input 添加监听事件,使其在值变动,触发更新操作

  3. 同 2 ,添加鼠标滑过时的事件监听

  4. 编写处理更新操作的方法

    1. 获取参数值后缀
    • 获取参数名(blur、spacing、color)
    • 获取参数值(12px、#efefef)
    • 赋值给对应的 CSS 变量
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Scoped CSS Variables and
    JS
  </title>
</head>

<body>
  <h2>Update CSS Variables with <span class='hl'>JS</span></h2>

  <div class="controls">
    <label for="spacing">Spacing:</label>
    <input type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">

    <label for="blur">Blur:</label>
    <input type="range" name="blur" min="0" max="25" value="10" data-sizing="px">

    <label for="base">Base Color</label>
    <input type="color" name="base" value="#8aa8af">
  </div>
  <code class="result">
		img {
			padding: <label id="code-spacing">100px</label>;
			filter: blur(<label id="code-blur">0px</label>);
		  background: <label id="code-base">#8aa8af</label>;
		}
	</code>

  <img class="img" src="https://source.unsplash.com/7bwQXzbF6KE/800x500">

  <style>
    /*
      misc styles, nothing to do with CSS variables
    */
    :root {
      --base: #8aa8af;
      --spacing: 100px;
      --blur: 0px;
    }

    body {
      text-align: center;
    }

    body {
      background: #193549;
      color: white;
      font-family: 'helvetica neue', sans-serif;
      font-weight: 100;
      font-size: 50px;
    }

    .controls {
      margin-bottom: 50px;
    }

    input {
      width: 100px;
    }

    .hl {
      color: var(--base);
    }
.result{
  font-size: 0.5em;
}
    .img {
      padding: var(--spacing);
      background: var(--base);
      filter: blur(var(--blur));
    }
  </style>

  <script>



const inputs = document.querySelectorAll('.controls input');	  
	  
	  function handleUpdate() {
		  const suffix = this.dataset.sizing || ''; // 根据 data-sizing 获取参数的后缀
		  document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); // 设置页面 CSS 变量的值
		  document.getElementById(`code-${this.name}`).innerText = this.value + suffix; // 页面参数实时显示
	  }
	  
	  inputs.forEach( input => input.addEventListener('change', handleUpdate));
	  inputs.forEach( input => input.addEventListener('mousemove', handleUpdate)); // 在滑块拖动过程中也实时变化
	  

  </script>

</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值