掌握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>

東哥筆記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章