web APIs基础-操作元素样式属性(一)

  • 可以通过JS设置/修改标签元素的样式属性
  • 比如通过轮播图小圆点自动更换元素样式(要复习)
  • 点击按钮可以滚动图片,这是移动图片的位置left等等
  • 学习路径
    • 通过stule属性操作CSS
    • 操作类名(className)操作CSS
    • 通过classList操作类控制CSS
  • 通过style属性操作CSS
  • 语法:
    • 对象.style.样式属性=值
  • 例:
  •   <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>操作元素样式属性</title>
        <style>
            div {
                width: 300px;
                height: 300px;
                background-color: aqua;
            }
        </style>
    </head>
    <body>
        <div class="box"></div>
        <script>
            // 1.获取元素
            // 这里注意用div的话用加点,但用box需要写.box
            const div=document.querySelector('.box')
            // 2.操作样式属性,对象.style.样式属性='值' 别忘了跟单位
            box.style.width='100px'
            // 多组词使用小驼峰命名法
            box.style.backgroundColor='pink'
            box.style.border='2px solid blue'
        </script>
    </body>
    </html>
    
    • 特殊情况
      • body不需要获取直接document.body(页面里的body就行)
      • 例:
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>切换背景图片</title>
          <style>
              body {
                  background: url(./序号图片/img1.png) no-repeat top center;
              }
          </style>
      </head>
      <body>
          <script>
              function getRandom(N,M) {
                  return Math.floor(Math.random()*(M-N+1))+N
              }
              let random=getRandom(1,4)
              document.body.style.background=`url('./序号图片/img${random}.png')`
          </script>
      </body>
      </html>
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值