简体   繁体   中英

Change css style on a keypress. (Vue.js)

I want whenever user presses a certain keybind, the value of css style of that element gets changed.

<textarea id="check"
    v-model="text"
    v-on:keydown.ctrl.up="decreaseFont"
 >

I checked the decreaseFont function was called but value of font-size is not changing.

decreaseFont() {
      console.log("check")
      document.getElementById("check").style.fontSize--;
    }

Here's my CSS

div textarea {
  position: relative;
  font-size: $fontSize;
  color: white;
  height: 100vh;
  width: 100%;
  outline: none;
  border: none;
  margin: 0;
  padding: 0;
  resize: none;
  font-family: "Courier New", Courier, monospace;
}

Also I want the textview to take the whole screen without the scrollbar. That's why I used 100vh as height. But I'am still getting a scrollbar.

I reseted the margin and padding of body to 0.

在此处输入图像描述

Using getComputedStyle()

 var app = new Vue({ el: '#app', data: { text: '', fontSize: null }, methods: { decreaseFont() { this.fontSize--; } }, created: function () { var el = document.getElementById('check'); var style = window.getComputedStyle(el, null).getPropertyValue('font-size'); this.fontSize = parseFloat(style); } })
 div textarea { position: relative; font-size: 16px; height: 100vh; width: 100%; margin: 0; padding: 0; resize: none; font-family: "Courier New", Courier, monospace; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <textarea id="check" v-model="text" v-on:keydown.ctrl.up="decreaseFont":style="{'font-size': fontSize + 'px'}"> </textarea> </div>

Have a look:

<template>
  <div>
    <textarea
      id="check"
      v-model="text"
      v-on:keydown.enter="decrease = decrease-1"
      :style="{'font-size': decrease+'px'}"
    />
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      text: null,
      decrease: 30
    };
  }
};
</script>

<style>
body {
  margin: 0;
}
</style>

<style scoped>
div textarea {
  position: relative;
  color: black;
  height: 99vh;
  width: 100%;
  outline: none;
  border: none;
  overflow: hidden;
  margin: 0;
  padding: 0;
  resize: none;
  font-family: "Courier New", Courier, monospace;
}
</style>

I created a SandBox so you can have a look at how it works.


Note that I made the font size change on the enter key for the demonstration purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM