Home > Blockchain >  How can i change style of the body when my modal it will be open?
How can i change style of the body when my modal it will be open?

Time:04-13

How can i change the body{overflow:hidden} when my modal it will be open?

for example it will be my modal, when its open, i would like to apply this style body{overflow:hidden}

<div  v-if="dialogFoundation">

i am using vuejs3, i am using setup(){...}

CodePudding user response:

The best performance would be to use javascript plain. You can add Eventlistener top the modal trigger Element. In my example i use a button. If it triggered then you can use classList and assign the body a class. In my example .dark.

Vue version

<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
  <div id="app">
    <h1>{{message}}</h1>
    <p></p>

    <button @click="doSomething">Modal</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Welcome to Vue!'
    };
  },
  methods: {
    doSomething() {
      const b = document.querySelector('body');
  b.classList.toggle('dark');
    }
  }
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

a,
button {
  color: #4fc08d;
}

button {
  background: none;
  border: solid 1px;
  border-radius: 2em;
  font: inherit;
  padding: 0.75em 2em;
}
.dark {
  background: black;
  opacity: 0.4;
}
</style>

Vanilla JS

const btn = document.querySelector('button');

btn.addEventListener('click', () => {
  const b = document.querySelector('body');
  b.classList.toggle('dark');
})
.dark {
  background: black;
  opacity: 0.4;
}
<body>
  <div></div>
  <button>click</button>
</body>

CodePudding user response:

You can use watchers in Vue.js for solving this problem. When variables changes you can check whether it is true or not, and if true change overflow of body to hidden.

{
    watch: {
         dialogFoundation(dialogFoundation) {
             document.body.style.overflow = dialogFoundation ? "hidden" : "auto"
         }
    }
}

But I think this is not good solution. You can set this styles to your app element

#app {
    width: 100%;
    height: 100%;
    overflow: auto;
}

and you can change style of app element using Vue directives.

CodePudding user response:

<template>
  <div id="app" :>
      Long text....
  </div>
</template>
<script>
import { ref } from "vue";
export default {
  setup() {
    const dialogFoundation = ref(true);
    return { dialogFoundation };
  },
};
</script>
<style>
html,
body,
#app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#app {
  overflow: auto;
}

#app.hidden {
  overflow: hidden;
}
</style>

Code in codesandbox - https://codesandbox.io/s/immutable-glitter-rwc2iy?file=/src/App.vue

  • Related