掌握vue之绑定样式

绑定内联样式(style属性):

做法: 将整个style属性,看作一个对象来绑定:

	1). HTML中: <元素 :style="变量">
                          "css属性:值; css属性:值;..."
	2).在 new Vue({
			data:{
				变量:{
					Css属性:值, 
					Css属性:值,
						... : ...
				}
			}
		})

优点: 非常便于只修改其中某一个css属性!
示例: 绑定style控制模拟飞机飞行

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #app > div {
        width: 100px;
        height: 100px;
        background-color: blue;
        position: fixed;
        left: 50%;
        bottom: 0;
      }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>

  <body>
    <div id="app">
      <div :style="style">
        <p>模拟飞机</p>
      </div>
    </div>

    <script>
      var vm = new Vue({
        el: "#app",
        data: {
          // 不好: style:"margin-left:-100px;bottom:0"
          //                   ↑
          style: {
            //可自动翻译为 |
            marginLeft: "-100px", //必须带单位!
            bottom: 0, //只有0特殊,可以不加单位
          },
        },
      });
      //当在窗口中按下键盘时
      window.onkeydown = function (e) {
        //如果按的是上键,则bottom+10
        if (e.keyCode == 38) {
          //vm.style //{ marginLeft:"-100px", bottom:0 }
          //只取出vm对象中style属性中bottom的值,转为整数
          var bottom = parseInt(vm.style.bottom);
          //将bottom+10,再保存回vm.style.bottom中,记得加单位
          vm.style.bottom = bottom + 10 + "px";
        } else if (e.keyCode == 40) {
          //否则如果按的是下键,则bottom-10
          //只取出vm对象中style属性中bottom值,转为整数
          var bottom = parseInt(vm.style.bottom);
          //将bottom-10,再保存回vm.style.bottom中,记得加单位
          vm.style.bottom = bottom - 10 + "px";
        } else if (e.keyCode == 37) {
          //否则如果按的是左键,则marginLeft-10
          //只取出vm对象中style属性中marginLeft值,转为整数
          var marginLeft = parseInt(vm.style.marginLeft);
          //将marginLeft-10,再保存回vm.style.marginLeft中,记得加单位
          vm.style.marginLeft = marginLeft - 10 + "px";
        } else if (e.keyCode == 39) {
          //否则如果按的是右键,则marginLeft+10
          //只取出vm对象中style属性中marginLeft值,转为整数
          var marginLeft = parseInt(vm.style.marginLeft);
          //将marginLeft+10,再保存回vm.style.marginLeft中,记得加单位
          vm.style.marginLeft = marginLeft + 10 + "px";
        }
      };
    </script>
  </body>
</html>

东哥笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值