条件CSS - 悬停 - 溢出

Gré*_*EUT 5 html css

我想在文本太长时隐藏文本,并在将鼠标悬停在文本上时显示它。

问题是当文本没有溢出时它也会触发。如何添加条件“如果文本溢出则执行翻译,如果文本没有溢出则不执行翻译”

如果可能的话,我更喜欢css解决方案而不是javascript解决方案,以避免不必要的复杂性(每次有文本时我都需要使用它)

PS:解决方案可以是scss标记。

.case {
  cursor: pointer;
  display: flex;
  width: 10em;
  height: 3em;
  overflow: hidden;
  background-color: #444444;
  color: white;
  margin-top: 2em;
  margin-bottom: 2em;
  flex-direction: row;
  align-items: center;
}

.sp {
  width: 100%;
  height: auto;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;
}

.case:hover .sp {
  transition: 1.3s;
  overflow: inherit;
  margin-left: -100%;
  width: auto;
  text-overflow: inherit;
  transition-timing-function: linear;
}
Run Code Online (Sandbox Code Playgroud)
<div class="case">
  <span class="sp">Short text</span>
</div>

<div class="case">
  <span class="sp">Overflowing long text, so long that you can't read it at once!</span>
</div>
Run Code Online (Sandbox Code Playgroud)

Pio*_*ski 2

你可以只用 css 来实现你想要的,但解决方案不是超级干净,需要额外的 html 标记(嵌套 div),并且将来可能会中断,但如果你坚持不使用 js 来实现,你可以看到下面的解决方案:

.case {
  cursor: pointer;
  display: flex;
  width: 10em;
  height: 3em;
  overflow: hidden;
  background-color: #444444;
  color: white;
  margin-top: 2em;
  margin-bottom: 2em;
  flex-direction: row;
  align-items: center;
}

.sp {
  flex: 1 0 100%;
  height: auto;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;
}

.case:hover .sp {
  transition: 1.3s;
  overflow: inherit;
  margin-left: -100%;
  text-overflow: inherit;
  transition-timing-function: linear;
}

.case:hover .case-wrapper {
  overflow: visible;
  margin-left: 100%;
  transition: 1.3s;
  transition-timing-function: linear;
}
.case-wrapper {
  text-overflow: inherit;
  overflow: hidden;
  flex: 1 0 100%;
  display: flex;
}
Run Code Online (Sandbox Code Playgroud)
<div class="case">
  <div class="case-wrapper">
  <span class="sp">Short text</span>
  </div>
</div>

<div class="case">
  <div class="case-wrapper">
  <span class="sp">Overflowing long text, so long that you can't read it at once!</span>
</div>
  </div>

<div class="case">
  <div class="case-wrapper">
  <span class="sp">It will always scroll all the way to the end and will stop there.</span>
</div>
  </div>
Run Code Online (Sandbox Code Playgroud)