css 如何检测占位符文本在输入字段中溢出?

uinbv5nw  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(114)

我的问题是有没有办法使用JavaScript或CSS来检测输入字段的占位符是否溢出?我们有很多方法来查找输入字段中输入的值是否溢出。我们可以使用scroll widthoffset width来实现这一点。但是滚动宽度对占位符不起作用。我们可以给予CSS的text-overflow: ellipsis来显示溢出占位符上的省略号。但是我找不到任何CSS或Javascript方法来检测省略号是否应用于保持器或占位符文本是否在输入字段中溢出。
请分享你的想法。

xlpyo6sf

xlpyo6sf1#

很简单:

const isPlaceholderOverflowed = inputId => {
  const input = document.getElementById(inputId);
  input.value = input.placeholder;
  const isOverflowed = input.scrollWidth > input.clientWidth;
  input.value = "";
  return isOverflowed;
}
jogvjijk

jogvjijk2#

感谢@MasihJahangiri的回答,我设法在Angular -14:

@Directive({
    selector: '[AutoResizeInput]',
})
export class AutoResizeInputDirective implements OnInit {
    @Input() clientPlaceholder = '';

    constructor(private elementRef: ElementRef) {}

    ngOnInit(): void {
        const input = this.elementRef.nativeElement;

        if (!this.clientPlaceholder.length || this.clientPlaceholder == undefined || this.clientPlaceholder == null) {
            throw new Error('AutoResizeInputDirective - Input element must have "clientPlaceholder" property defined!');
        }

        input.setAttribute('value', this.clientPlaceholder);
        const css = `width: ${input.scrollWidth}px`;
        this.elementRef.nativeElement.setAttribute('style', css);
        input.value = '';
    }
}

在模板中添加了Input元素:

<input
    cbpAutoResizeInput
    [clientPlaceholder]="item.placeholder"
    ... />

相关问题