JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.4.1/lib/index.js"></script>
<script src="//unpkg.com/focus-outside@0.5.0/lib/index.js"></script>
<div id="app">
<el-dropdown ref="dropdown" trigger="click">
<span class="el-dropdown-link">
下拉菜单<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu ref="dropdownContent" slot="dropdown">
<el-dropdown-item>黄金糕</el-dropdown-item>
<el-dropdown-item>狮子头</el-dropdown-item>
<el-dropdown-item>螺蛳粉</el-dropdown-item>
<el-dropdown-item>双皮奶</el-dropdown-item>
<el-dropdown-item>蚵仔煎</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-select v-model="selectedValue"
ref="selectContent" popper-class="my-select focus-outside" @click.native="bindSelectFocus">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-date-picker
v-model="month"
ref="datePicker"
type="month"
popper-class="my-date-picker"
placeholder="选择月"
@click.native="bindFocus">
</el-date-picker>
</div>
<iframe src="//baidu.com"></iframe>
SCSS
@import url("//unpkg.com/element-ui@2.4.1/lib/theme-chalk/index.css");
iframe {
width: 100%;
height: 300px;
}
.focus-outside {
outline: none;
}
Babel + JSX
const { bind: focusBind, unbind: focusUnbind } = FocusOutside
new Vue({
mounted () {
// 为 dropdown 绑定
focusBind(this.$refs.dropdown.$el, this.$refs.dropdown.hide)
focusBind(this.$refs.dropdownContent.$el, this.$refs.dropdown.hide)
},
destoryed () {
if (this.myDatePicker) {
focusUnbind(this.myDatePicker, this.$refs.datePicker.hidePicker)
focusUnbind(this.$refs.datePicker.$el, this.$refs.datePicker.hidePicker)
}
if (this.mySelect) {
focusUnbind(this.mySelect, this.$refs.selectContent.handleClose)
focusUnbind(this.$refs.selectContent.$el, this.$refs.selectContent.handleClose)
}
focusUnbind(this.$refs.dropdown.$el, this.$refs.dropdown.hide)
focusUnbind(this.$refs.dropdownContent.$el, this.$refs.dropdown.hide)
},
data () {
return {
month: '',
initBindDatePicker: false,
initBindSelect: false,
mySelect: null,
myDatePicker: null,
selectedValue: '',
options: [{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}]
}
},
methods: {
bindFocus () {
if (this.initBindDatePicker) return
this.initBindDatePicker = true
this.myDatePicker = document.querySelector('.my-date-picker')
// 为 datePicker 绑定 focusOutside。
focusBind(this.$refs.datePicker.$el, this.$refs.datePicker.hidePicker)
focusBind(this.myDatePicker, this.$refs.datePicker.hidePicker)
},
bindSelectFocus () {
if (this.initBindSelect) return
this.initBindSelect = true
this.mySelect = document.querySelector('.my-select')
// 为 select 绑定 focusOutside。
focusBind(this.mySelect, this.$refs.selectContent.handleClose)
focusBind(this.$refs.selectContent.$el,...