在Angular中实现一个级联效果的下拉框的示例代码


Posted in Javascript onMay 20, 2020

实现一个具有级联效果的下拉搜索框,实现的结果如下图所示

在Angular中实现一个级联效果的下拉框的示例代码

我们主要通过这个组件,来学习一些细微的逻辑,比如: 如何计算input框内文字的长度; 如何获取光标的位置;如何实现滚动条随着上下键盘的按动进行移动......

具体需求如下

  1. 级联搜索最多不超过三级,以”.“作为级联搜索的连接符
  2. 搜索框跟着文本框中的”.“进行向后移动,向右移动的最大距离不能超过文本框的宽度
  3. 当用户修改之前的级联内容,则不进行搜索,并隐藏搜索框;若用户在之前输入的是”.“, 则将此”.“之后的内容全部删除并搜索当前的相关内容

接下来我们根据需求,来写我们的逻辑

首先我们搭建html页面

<input
    #targetInput
    autocomplete="off"
    nz-input
    [(ngModel)]="searchValue"
    (keydown)="handlePress($event)"
    (input)="handleSearchList()"/>
   
   <div #searchList class="search-popup" [hidden]="!visible" (keyDown)="onKeydown($event)">
     <nz-spin [nzSpinning]="searchLoading" [class.spinning-height]="searchLoading">
      <div class="data-box" *ngIf="searchData && searchData.length !== 0">
       <ul>
       // 这里在上篇文章中已经讲解过,如何实现让匹配的文字高亮显示~
        <li
         id="item"
         *ngFor="let item of searchData;let i = index;"
         [class.item-selected]="curIndex === i"
         (mouseover)='hoverDataItem(i)'
         (click)="onSelectClick(item)">
         <span [innerHTML]="item | highlightSearchResult:searchValue | safe: 'html'"></span>
        </li>
       </ul>
      </div>
     </nz-spin>
   </div>
.search-popup {
 height: 376px;
 width: 246px;
 overflow-y: auto;
 box-shadow: 0 2px 8px rgba(0,0,0,.15);
 border-radius: 4px;
 position: absolute;
 background-color: #fff;
 z-index: 999;
 top: 92px;
 right: 61px;

 .data-box {
  margin: 0 10px;

  &:not(:last-child) {
   border-bottom: 1px solid #E4E5E7;
  }

  .no-search-data {
   display: inline-block;
   width: 100%;
   text-align: center;
   color: #C3C9D3;
   line-height: 40px;
  }
 }

 & ul {
  margin: 0 -10px;
  margin-bottom: 0;
  text-align: left;
 }

 & li {
  padding: 3px 10px;
  position: relative;
  list-style: none;
  height: 32px;
  line-height: 26px;
  &:hover {
   cursor: pointer;
   background-color: #e6f7ff;
  }
  &.item-selected {
   background-color: #E6F7FF;
  }
 }

 &.item-selected {
  background-color: #E6F7FF;

 }

.hidden-box {
 display: inline-block;
 border: 1px solid #ddd;
 visibility: hidden;
}

实现相关的逻辑

根据前两个需求,我们需要根据文本框中的”.“进行向后移动,向右移动的最大距离不能超过文本框的宽度。

思路: 我们需要将文本框中的字符串根据”.“来转换成数组,并且要想办法获取文本框中文字的长度。
如何获取文本框中文字的长度呢?
我们可以将文字的内容,重新放到一个display: inline-block的div容器中,然后获取容器的宽度,如下代码所示~

// html
 <!-- 用于测量input框的文字宽度 -->
 <div class="hidden-box" #firstLevel></div> // 以”.“转化的数组,下标为0的内容的宽度
 <div class="hidden-box" #secondLevel></div> // 以”.“转化的数组,下标为1的内容的宽度
 <div class="hidden-box" #allLevel></div> // 整个文本框的文字的宽度
 
 // ts
 import { ElementRef, Renderer2 } from '@angular/core';
 
 export class SearchListComponent {
  @ViewChild('searchList', { static: true }) public searchList: ElementRef;
  @ViewChild('firstLevel', { static: true }) public firstLevel: ElementRef;
  @ViewChild('secondLevel', { static: true }) public secondLevel: ElementRef;
  @ViewChild('allLevel', { static: true }) public allLevel: ElementRef;
  constructor(private _renderer: Renderer2) {}
     
  public setSearchPosition(rightValue: string): void {
    this._renderer.setStyle(
     this.searchList.nativeElement,
     'right',
     rightValue);
   } 
   
  public setSearchListPosition(targetValue: string): void {
  const inputWidth = 217;
  const defaultRightPosition = 60;
  const maxRightPosition = -148;
  const firstLevel = this.firstLevel.nativeElement;
  const secondLevel = this.secondLevel.nativeElement;
  const allLevel = this.allLevel.nativeElement;
  const targetValueArr = targetValue ? targetValue.split('.') : [];

  // 将input中的内容,根据”.“转换成数组之后,将相关的内容赋值到新的div容器中,为了便于获取文字的宽度
  allLevel.innerHTML = targetValue;
  firstLevel.innerHTML = targetValueArr && targetValueArr[0];
  secondLevel.innerHTML = targetValueArr && targetValueArr.length > 1 ? targetValueArr[1] : '';

  // 得到相关宽度之后,实现下拉框移动的逻辑
  if (firstLevel.offsetWidth >= inputWidth
   || (firstLevel.offsetWidth + secondLevel.offsetWidth) >= inputWidth
   || allLevel.offsetWidth >= inputWidth) {
    this.setSearchPosition(this._renderer, this.searchList, `${maxRightPosition}px`);
   } else if (targetValueArr.length <= 1) {
   this.setSearchPosition(this.renderer, this.searchList, '61px');
  } else if (targetValueArr.length <= 2) {
   this.setSearchPosition(this.renderer, this.searchList, `${defaultRightPosition - firstLevel.offsetWidth}px`);
  } else if (targetValueArr.length <= 3) {
   this.setSearchPosition(renderer,
               this.searchList,
               `${defaultRightPosition - firstLevel.offsetWidth - secondLevel.offsetWidth}px`);
  }
 }
 }

到这里,我们可以完成第一和第二个需求,我们再来看看第三个需求: 主要是根据用户输入的位置以及修改的内容,来决定是否显示搜索和显示下拉框,如果用户输入的不是”.“我们则不显示,如果用户在之前的级联中输入”.“我们就需要进行再次帮用户搜索结果。

思路: 要想完成需求三,我们需要知道用户到底是在哪里操作,即我们要是可以知道光标的位置就更完美了~

// 获取光标的位置
 public getCursorPosition(element: HTMLInputElement): number {
  let cursorPosition = 0;
  if (element.selectionStart || element.selectionStart === 0) {
   cursorPosition = element.selectionStart;
  }
  return cursorPosition;
 }
 
 // 用来获取用户输入的内容是什么
 public handlePress(event: KeyboardEvent): void {
   this.curPressKey = event.key;
  }

 // 用户input的时候调用的核心方法
 public handleSearchList(value: string): void {
  this.curIndex = 0;
  const cursorPosition = this.getCursorPosition(this.targetInput.nativeElement); // 获取光标位置
  let targetValue = value;
  const targetValueArr = targetValue ? targetValue.split('.') : [];
  const valueArrLength = targetValueArr.length;
  this.setSearchListPosition(targetValue); // 调整位置
  // 判断那些情况下应该搜索并显示下拉框
  if (valueArrLength === 1
   || valueArrLength === 2 && cursorPosition >= targetValueArr[0].length + 1
   || valueArrLength === 3 && cursorPosition >= targetValueArr[0].length + targetValueArr[1].length + 2) {
    this.searchLoading = true;
    this.visible = true;
    ...获取下拉框中的数据
  } else {
   this.hidePopup();
  }
 }

最后为了更好的提高用的体验,我们还需要让下拉框支持键盘事件哦~方法也很简单,如下所示

public onKeydown(keyDownInfo: {index: number, code: number, e: KeyboardEvent}): void {
  const { code, e } = keyDownInfo;
  e.stopPropagation();
  if (code === 38) { // 键盘上
   e.preventDefault(); // 防止光标由最后边移动到前边,只是在开发中遇到的一点体验上小问题
   if (this.curIndex > 0) {
    this.curIndex--;
   }
  } else if (code === 40) { // 键盘下
   if (this.curIndex < this.searchData.length - 1) {
    this.curIndex++;
   }
  } else if (code === 13) {  // 回车,即相当于用户点击
   this.ruleModal.showModal();
   const curData = this.searchData[this.curIndex];
   if (curData) {
    this.onSelectClick(curData);
   }
  }
  // 实现下拉框的滚动条随着键盘的上下键按动时一起移动
  const lis = document.querySelectorAll('#item');
  const curLiEle = lis[this.curIndex] as HTMLElement;
  const searchList = this.searchList.nativeElement;
  const liEleHeight = 32;
  //(当前选中li标签的offsetTop + li标签自身的高度 - 下拉框的高度)
  searchList.scrollTop = curLiEle.offsetTop + liEleHeight - searchList.clientHeight;
 }

总结

其实这个级联搜索的组件,他的通用性可能并不是很强,但是在实现的过程中,一些细节逻辑的通用性还是比较强的~ 希望这些细节可以给同在开发中的你带来一些帮助~❤

到此这篇关于在Angular中实现一个级联效果的下拉框的示例代码的文章就介绍到这了,更多相关Angular级联下拉框内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
FF IE兼容性的修改小结
Sep 02 Javascript
提高jQuery性能的十个诀窍
Nov 14 Javascript
分享Javascript中最常用的55个经典小技巧
Nov 29 Javascript
js通过更改按钮的显示样式实现按钮的滑动效果
Apr 23 Javascript
JavaScript通过元素的ID和name设置样式
Jul 08 Javascript
JavaScript判断一个字符串是否包含指定子字符串的方法
Mar 18 Javascript
一步一步封装自己的HtmlHelper组件BootstrapHelper(三)
Sep 14 Javascript
jquery实现表单获取短信验证码代码
Mar 13 Javascript
AngularJS日期格式化常见操作实例分析
May 17 Javascript
vue2.0父子组件间传递数据的方法
Aug 16 Javascript
vue-router启用history模式下的开发及非根目录部署方法
Dec 23 Javascript
微信小程序学习总结(五)常见问题实例小结
Jun 04 Javascript
vue模块移动组件的实现示例
May 20 #Javascript
vue父子组件间引用之$parent、$children
May 20 #Javascript
jQuery HTML获取内容和属性操作实例分析
May 20 #jQuery
微信小程序国际化探索实现(附源码地址)
May 20 #Javascript
jQuery HTML设置内容和属性操作实例分析
May 20 #jQuery
jquery html添加元素/删除元素操作实例详解
May 20 #jQuery
jQuery HTML css()方法与css类实例详解
May 20 #jQuery
You might like
使用PHP备份MySQL和网站发送到邮箱实例代码
2013/11/28 PHP
PHP错误Parse error: syntax error, unexpected end of file in test.php on line 12解决方法
2014/06/23 PHP
PHP实现获取图片颜色值的方法
2014/07/11 PHP
php读取文件内容的方法汇总
2015/01/24 PHP
php 无限级分类 获取顶级分类ID
2016/03/13 PHP
PHP记录和读取JSON格式日志文件
2016/07/07 PHP
PHP CodeIgniter分页实例及多条件查询解决方案(推荐)
2017/05/20 PHP
javascript设计模式 接口介绍
2012/07/24 Javascript
JS+CSS实现另类带提示效果的竖向导航菜单
2015/10/15 Javascript
jquery中ajax处理跨域的三大方式
2016/01/05 Javascript
jQuery中on绑定事件后引发的事件冒泡问题如何解决
2016/05/25 Javascript
js调用刷新界面的几种方式
2017/05/03 Javascript
使用JS动态显示文本
2017/09/09 Javascript
fullpage.js最后一屏滚动方式
2018/02/06 Javascript
JavaScript使用math.js进行精确计算操作示例
2018/06/19 Javascript
在vue中使用公共过滤器filter的方法
2018/06/26 Javascript
浅析vue中的MVVM实现原理
2019/03/04 Javascript
javascript中的with语句学习笔记及用法
2020/02/17 Javascript
Javascript ParentNode和ChildNode接口原理解析
2020/03/16 Javascript
基于vue-simple-uploader封装文件分片上传、秒传及断点续传的全局上传插件功能
2021/02/23 Vue.js
[56:00]DOTA2上海特级锦标赛主赛事日 - 4 胜者组决赛Secret VS Liquid第一局
2016/03/05 DOTA
Python 元组(Tuple)操作详解
2014/03/11 Python
Python入门及进阶笔记 Python 内置函数小结
2014/08/09 Python
Python 序列化 pickle/cPickle模块使用介绍
2014/11/30 Python
pycharm下查看python的变量类型和变量内容的方法
2018/06/26 Python
transform python环境快速配置方法
2018/09/27 Python
Python读取mat文件,并保存为pickle格式的方法
2018/10/23 Python
导入tensorflow时报错:cannot import name 'abs'的解决
2019/10/10 Python
python实现在多维数组中挑选符合条件的全部元素
2019/11/26 Python
pytorch中的transforms模块实例详解
2019/12/31 Python
python 发送邮件的四种方法汇总
2020/12/02 Python
一年级家长会邀请函
2014/01/25 职场文书
焦裕禄精神心得体会
2014/09/02 职场文书
2014年安全工作总结范文
2014/11/13 职场文书
2015年预防青少年违法犯罪工作总结
2015/05/22 职场文书
浅谈CSS不规则边框的生成方案
2021/05/25 HTML / CSS