仿el-select实现点击按钮显示下拉框

实现点击按钮显示下拉框,点击下拉框外面部分下拉框关闭(点击下拉框里面部分下拉框不关闭)。

实现效果:

在这里插入图片描述

实现代码:

<template>
  <div style="position: relative;">
    <button ref="selectButton" @click="toggleDropdown">显示下拉框</button>
    <div v-if="isDropdownVisible" ref="dropdown" class="dropdown">
      <!-- 下拉框内容 -->
      <!-- ... -->
    </div>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      isDropdownVisible: false, // 下拉框的显示状态
    };
  },
  mounted() {
    
    
    // 监听点击事件,用于关闭下拉框
    window.addEventListener('click', this.handleClickOutside);
  },
  beforeUnmount() {
    
    
    // 移除点击事件监听器
    window.removeEventListener('click', this.handleClickOutside);
  },
  methods: {
    
    
    toggleDropdown() {
    
    
      this.isDropdownVisible = !this.isDropdownVisible; // 切换下拉框的显示状态
    },
    handleClickOutside(event) {
    
    
      // 判断点击事件的目标是否在下拉框内部或按钮内部,如果不在,则关闭下拉框
      if (this.$refs.dropdown 
          && !this.$refs.dropdown.contains(event.target) 
          && !this.$refs.selectButton.contains(event.target)) {
    
    
        this.isDropdownVisible = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
  
.dropdown {
    
    
  position: absolute;
  top: 100%; /* 下拉框相对于按钮的位置 */
  left: 0;
  width: 200px;
  background-color: #cc2424;
  border: 1px solid #ccc;
  padding: 10px;
  z-index: 9999;
}
</style>

注意上面实现效果和这个实现代码稍微有点不一样,不过差不多,因为实现效果是实际项目的,里面代码太复杂了,这边就把最基本的功能代码写出来。
注意:这里用的是vue3.

在上述示例中,通过在mounted生命周期钩子中添加点击事件的监听器,监听整个窗口的点击事件。在beforeUnmount生命周期钩子中移除事件监听器,以避免在组件销毁时仍然监听点击事件。

在handleClickOutside方法中,判断点击事件的目标是否在下拉框的DOM元素内部或按钮的DOM元素内部。如果点击的目标既不在下拉框内部,也不是按钮本身,则将isDropdownVisible设置为false,从而关闭下拉框。

通过以上方式,你可以实现点击下拉框以外的任意位置关闭下拉框的功能。

猜你喜欢

转载自blog.csdn.net/qq_43651168/article/details/131236059
今日推荐