在样式表中,使用媒体查询以确保搜索栏布局适合移动设备屏幕大小:
@media (max-width: 767px) { /* 移动设备样式 / .search-bar { / 设置合适的宽度和高度 */ width: 100%; height: 50px; } }
移动端浏览器可能会默认启用触摸事件,而不是鼠标事件。因此,在移动端上搜索栏无法正常工作。禁用默认事件可以解决此问题:
import { Component, ElementRef, OnInit, OnDestroy } from '@angular/core'; import { Router } from '@angular/router';
@Component({ selector: 'app-search-bar', templateUrl: './search-bar.component.html', styleUrls: ['./search-bar.component.css'] }) export class SearchBarComponent implements OnInit, OnDestroy {
constructor(private elementRef: ElementRef, private router: Router) { }
ngOnInit() { this.elementRef.nativeElement.querySelector('.search-input') .addEventListener('touchend', function(e) { e.stopPropagation(); }); }
ngOnDestroy() { this.elementRef.nativeElement.querySelector('.search-input') .removeEventListener('touchend'); }
}
在ngOnInit函数中,addEventListener代码段会在元素的class为“search-input”的子元素(即搜索栏的输入框)被触摸后执行。stopPropagation()将停止事件传播,防止浏览器默认处理事件。
在ngOnDestroy函数中,removeEventListener代码段将在元素销毁时执行,将事件处理器从元素中删除。
这将确保在移动设备上使用触摸事件时,搜索栏正常工作。
下一篇:Angular2依赖注入抽象类。