一、在Index中添加自定义指令v-pin
给组件绑定@click属性
<div v-pin="card1.pinned" class="card"><button @click="card1.pinned=!card1.pinned">钉住/取消1</button>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
<div v-pin="card2.pinned" class="card"><a href="#" @click="card2.pinned=!card2.pinned">钉住/取消2</a>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
<div v-pin="card3.pinned" class="card"><a href="#" @click="card3Fucntion">钉住/取消3</a>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
添加初始样式.card
<style>
.card{
width:350px;
background: #ccc;
padding: 10px;
margin:5px;
}
</style>
二、在main.js中定义指令
binding.value用来获取html中v-pin的值
Vue.directive('pin', function(el,binding){
var pinned=binding.value;
if(pinned){
el.style.position='fixed';
el.style.top='10px';
el.style.left='10px';
}else{
el.style.position='static';
}
});
初始化属性及函数
new Vue({
el: '#app',
data:{
card1:{
pinned:false,
},
card2:{
pinned:false,
},
card3:{
pinned:false,
}
},
methods:{
card3Fucntion:function(){
this.card3.pinned=!this.card3.pinned;
}
},
});
三、效果展示
点击“钉住/取消按钮”
该div固定在页面上不随着滚动
四、本篇完整代码
index.html
<div id="app">
<div v-pin="card1.pinned" class="card"><button @click="card1.pinned=!card1.pinned">钉住/取消1</button>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
<div v-pin="card2.pinned" class="card"><a href="#" @click="card2.pinned=!card2.pinned">钉住/取消2</a>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
<div v-pin="card3.pinned" class="card"><a href="#" @click="card3Fucntion">钉住/取消3</a>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<div>select *from paymentlog where businessno='DZBV202021020000002121 ';
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</div>
main.js
Vue.directive('pin', function(el,binding){
var pinned=binding.value;
if(pinned){
el.style.position='fixed';
el.style.top='10px';
el.style.left='10px';
}else{
el.style.position='static';
}
});
new Vue({
el: '#app',
data:{
card1:{
pinned:false,
},
card2:{
pinned:false,
},
card3:{
pinned:false,
}
},
methods:{
card3Fucntion:function(){
this.card3.pinned=!this.card3.pinned;
}
},
});