JavaScript小项目03-CSS Variables

03-CSS Variables

功能主要就是当鼠标滑动的时候,改变相应的边框值、清晰度以及背景颜色

效果图:

主要代码:

<!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 id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px" data-sizing="px">

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

    <label for="base">Base Color</label>
    <input id="base" type="color" name="base" value="#ffc600">
  </div>

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

  <style>
    /* 下面的两个都是css的自定义属性 */
    .root{
      --spacing:5px;
      --blur:2px;
      --base:yellow
    }

    img{
      padding: var(--spacing);
      filter: blur(var(--blur));
      background: var(--base);
    }

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

    .controls {
      margin-bottom: 50px;
    }

    input {
      width: 100px;
    }
  </style>

  <script>
    // 这是第一种写法,虽然这种写法能够实现功能,但是这种写法也会产生弊端,如果我们在调用函数updateInput的时候需要多次判断就很繁琐,所以引出第二种写法如下:
    // // 首先获取所有的input标签
    // const input =document.querySelectorAll('.controls input')
    // // 获取图片
    // const img =document.querySelector('img')

    // // 函数判断如果是边框改变则改变padding,如果是背景颜色改变则改变background,如果是清晰度则改变blur
    // function updateInput(){
    //   if(this.name==='spacing'){
    //     img.style.padding =this.value+'px'
    //   }
    //   if(this.name === 'blur'){
    //     img.style.filter=`blur(${this.value}px)`
    //   }
    //   if(this.name === 'base'){
    //     img.style.background =this.value
    //   }
    // }

    // // 监听当input框内元素发生改变
    // input.forEach(input =>input.addEventListener('change',updateInput))

    // 这是第二种写法  首先需要在style中添加root
    const input =document.querySelectorAll('.controls input')
    const img =document.querySelector('img')

    function updateInput(){
      const str=this.dataset.sizing || ''
      // setProperty设置的是内联样式,有三个参数,但是一般来讲只写两个参数即可,第三个参数是改变优先级的
      document.documentElement.style.setProperty(`--${this.name}`,this.value+str)
      // documentElement:一个元素对象返回一个文档的文档元素。
    }

    input.forEach(input =>input.addEventListener('change',updateInput))
  </script>

</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值