【问题标题】:String value with commas separated and show in tooltip html用逗号分隔的字符串值并在工具提示 html 中显示
【发布时间】:2022-07-29 12:00:43
【问题描述】:

大家好,

我从我的 api 调用 code1、code2、code3、code4 中获取字符串值。 我想显示像 code1+ 这样的字段。 一旦用户将鼠标悬停在 code1+ 上,我希望结果如下所示。我尝试在 css 中使用省略号,但它不起作用。您能否让我知道您对如何在 html/Angular 中实现的意见。

        code1
        code2
        code3
        code4
    
    Thank you

【问题讨论】:

  • 显示使用你目前尝试过的代码。
  • CodeName
    Code1,code2,code3,code4
  • 对。你可能无法单独使用 css 解决这个问题。我建议将字符串拆分为一个数组,显示数组中的第一项(code1)并使用脚本(ngIf?)显示其余部分(鼠标悬停)。

标签: javascript html angular string angular10


【解决方案1】:

我们可以使用*ngIf 有条件地在鼠标悬停在父元素上的事件上渲染元素。当然,如果您还想将鼠标悬停在 span 上,我们需要考虑一些巧妙的方法,以便在用户移动元素时不触发 mouseout

<div (mouseout)="isHovering = false" (mouseover)="isHovering = true">
  <div *ngFor="let code of codes; index as i">
    <span *ngIf="i === 0 || isHovering === true">{{ code }}</span>
  </div>
</div>
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  string = 'code1,code2,code3,code4';
  codes = [];
  isHovering = false;
  ngOnInit() {
    of(this.string).subscribe((response) => {
      this.codes = response.split(',');
      console.log(this.codes);
    });
  }
}

工作示例:https://stackblitz.com/edit/angular-ivy-tu6uhl?file=src%2Fapp%2Fapp.component.ts

如果我们可以在 CSS 中用逗号分隔字符串,我们也可以制作这个纯 CSS,但我们不能,只有用空格分隔是可能的,所以我们需要使用 javascript 来预处理字符串。但在使用:hover 之后,我们要么显示字符串的“短”版本,要么显示“长”版本。

这样的 CSS 变体如下所示:

/* Container for the text that expands on hover */
.expanded-text {
  width: 100%;
}
/* Longer name hidden by default  */
span.longer-name{
  display:none;
}
/* On hover, hide the short name */
.expanded-text:hover span.short-name{
  display:none;
}
/* On hover, display the longer name.  */
.expanded-text:hover span.longer-name{
  display:block;
}
<div class="expanded-text">

  <span class="short-name">{{ codes[0] }}</span>

  <span class="longer-name">
    <ng-container *ngFor="let code of codes">
      {{ code }}
    </ng-container>
  </span>
  
</div>

工作示例:https://stackblitz.com/edit/angular-ivy-rbjgzr?file=src%2Fapp%2Fapp.component.css

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多