一、背景
有一個需求是要彈框後,焦點默認在某個按鈕上,確認或者取消。
二、
我還是用前幾話寫的彈框插件來說,爲了區分焦點在按鈕上還是不在,把之前的css稍微改了一下。文末會附上完整代碼。
1、沒有加這個效果之前
點開彈框,按鈕沒有效果
目標是做出,一打開彈框就是醬紫的~
知道怎麼做的話,寫起來就好簡單~
就是要等到DOM都加載完了再操作焦點。
// 彈框焦點默認在確認鍵
this.$nextTick(()=> {
$("#btnMsgBoxConfirm").focus();
});
在這個地方寫
整個的messageBox.vue貼一下
<template>
<div v-key-bind-listen>
<div class="msgBox" v-show="isShowMessageBox">
<div class="msgBox_header">
<div class="msgBox_title">
<h3>{{ title }}</h3>
</div>
</div>
<div class="msgBox_content">
<p>{{ content }}</p>
</div>
<div class="msgBox_btns">
<button type="button" class="btn btn-lime btn-lg" id="btnMsgBoxConfirm" @click="confirm">確定</button>
<button type="button" class="btn btn-lime btn-lg" id="btnMsgBoxCancel" @click="cancel">取消</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'messageBox',
data(){
return {
title: '',
content: '',
isShowMessageBox: false,
resolve: '',
reject: '',
promise: '' // 保存promise對象
}
},
methods: {
close(state){
this.model.show = false;
if(this.model.callback){
this.model.callback(state);
}
},
// 確定,將promise斷定爲resolve狀態
confirm: function () {
this.isShowMessageBox = false;
this.resolve('confirm');
this.remove();
},
// 取消,將promise斷定爲reject狀態
cancel: function () {
this.isShowMessageBox = false;
this.reject('cancel');
this.remove();
},
// 彈出messageBox,並創建promise對象
showMsgBox: function () {
this.isShowMessageBox = true;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
// 彈框焦點默認在確認鍵
this.$nextTick(()=> {
$("#btnMsgBoxConfirm").focus();
});
// 返回promise對象
return this.promise;
},
remove: function () {
setTimeout(() => {
this.destroy();
}, 300);
},
destroy: function () {
// this.$destroy();
// console.log(document.body.contains(this.$el))
// document.body.removeChild(this.$el);
// // 這邊判斷一下節點還是不是它的child了,是child才刪
// // 不然會報錯。其實這個報錯也沒啥影響,就是嚴謹一點
this.$destroy();
if (document.body.contains(this.$el)) {
document.body.removeChild(this.$el);
}
}
}
}
</script>
<style scoped>
.msgBox {
position: fixed;
z-index: 4;
left: 50%;
top: 35%;
transform: translateX(-50%);
width: 420px;
background-color: black;
opacity: 0.55;
}
.msgBox_header {
padding: 20px 20px 0;
}
.msgBox_title {
padding-left: 0;
margin-bottom: 0;
font-size: 26px;
font-weight: 800;
height: 18px;
color: greenyellow;
}
.msgBox_content {
padding: 30px 20px;
color: #fff;
font-size: 18px;
font-weight: bold;
text-align: center;
}
.msgBox_btns {
padding: 10px 20px 15px;
text-align: right;
overflow: hidden;
}
#btnMsgBoxCancel{
background-color: black;
}
#btnMsgBoxCancel:hover{
background-color: #35a963;
}
#btnMsgBoxCancel:focus{
background-color: #35a963;
}
#btnMsgBoxConfirm{
background-color: black;
}
#btnMsgBoxConfirm:focus{
background-color: #3bbd6e;
}
#btnMsgBoxConfirm:hover{
background-color: #3bbd6e;
}
@keyframes show-messageBox {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes bounce-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
好簡單喲~