使用插件
页面需要引入这个js
const elTransition =
"0.3s height ease-in-out, 0.3s padding-top ease-in-out, 0.3s padding-bottom ease-in-out";
const Transition = {
"before-enter"(el) {
el.style.transition = elTransition;
if (!el.dataset) el.dataset = {};
el.dataset.oldPaddingTop = el.style.paddingTop;
el.dataset.oldPaddingBottom = el.style.paddingBottom;
el.style.height = 0;
el.style.paddingTop = 0;
el.style.paddingBottom = 0;
},
enter(el) {
el.dataset.oldOverflow = el.style.overflow;
if (el.scrollHeight !== 0) {
el.style.height = el.scrollHeight + "px";
el.style.paddingTop = el.dataset.oldPaddingTop;
el.style.paddingBottom = el.dataset.oldPaddingBottom;
} else {
el.style.height = "";
el.style.paddingTop = el.dataset.oldPaddingTop;
el.style.paddingBottom = el.dataset.oldPaddingBottom;
}
el.style.overflow = "hidden";
},
"after-enter"(el) {
el.style.transition = "";
el.style.height = "";
el.style.overflow = el.dataset.oldOverflow;
},
"before-leave"(el) {
if (!el.dataset) el.dataset = {};
el.dataset.oldPaddingTop = el.style.paddingTop;
el.dataset.oldPaddingBottom = el.style.paddingBottom;
el.dataset.oldOverflow = el.style.overflow;
el.style.height = el.scrollHeight + "px";
el.style.overflow = "hidden";
},
leave(el) {
if (el.scrollHeight !== 0) {
el.style.transition = elTransition;
el.style.height = 0;
el.style.paddingTop = 0;
el.style.paddingBottom = 0;
}
},
"after-leave"(el) {
el.style.transition = "";
el.style.height = "";
el.style.overflow = el.dataset.oldOverflow;
el.style.paddingTop = el.dataset.oldPaddingTop;
el.style.paddingBottom = el.dataset.oldPaddingBottom;
}
};
export default {
name: "collapseTransition",
functional: true,
render(h, { children }) {
const data = {
on: Transition
};
return h("transition", data, children);
}
};
页面使用:
<div class="containers" style="background:red;height:600px;width:100%">
<button @click="isActive = !isActive">展开/折叠</button>
<collapse>
<div class="container" v-show="isActive">
内容
</div>
</collapse>
</div>
js
import collapse from "../assets/js/coll.js";
export default {
components: {
collapse
},
data() {
return {
isActive: false,
}
}
}
另外一种简单的
html
<div id="app">
<button @click="flag = !flag"></button>
<div :class="[flag ? 'light' : 'dark']">切换的元素</div>
<button @click="flag1 = !flag1"></button>
<div :class="[flag1 ? 'light1' : 'dark1']">切换的元素</div>
</div>
js
const vm = new Vue({
el:'#app',
data:{
flag:true,
flag1:false
}
})
</script>
style
html,
body,
#app {
height: 100%;
padding: 0;
margin: 0;
}
.light {
background-color: hotpink;
color: #000;
display:block;
}
.dark {
background-color: #000;
color: white;
display:none
}
.dark1{
display:block;
}
.light1{
display:none
}