0
<div style="width:100px; overflow:hidden; text-align:right;" id="pathdiv">

<script>
    document.getElementById("pathdiv").innerHTML="long/path/to/file"
</script>

我的目标是在相对较窄的 div 中显示一条长的绝对路径右对齐,以减少它的开头(以便显示路径的有趣部分)。上面的代码在适合 div 的情况下使文本右对齐,如果不适合则将其剪切,但不幸的是它剪切了它的结尾,而不是开头。

如果字符串太长,我可以手动修剪它,但是我必须以某种方式计算有多少字符使它适合(不清楚)。

他们是否有任何直接的方式来实现我的目标(使用 CSS 或其他方式)?

4

2 回答 2

1

<div style="width:100px; overflow:hidden; text-align:right;text-overflow:ellipsis; direction:rtl" id="pathdiv">

<script>
    document.getElementById("pathdiv").innerHTML="long/path/to/file"
</script>

添加方向(rtl)会起作用。

于 2017-12-21T13:55:12.733 回答
1

您可以在 div 内使用 span 并将其position:absolute设为right:0. 在这种情况下,您将获得所需的东西。

添加white-space:nowrap;内容中是否有空格以避免换行

document.querySelector("#pathdiv span").innerHTML="very/very/very-long/path/to/file"
#pathdiv {
  width: 100px;
  overflow: hidden;
  text-align: right;
  position: relative;
}
#pathdiv:before {
 content:"A"; /* Hidden character to create the needed space*/
 visibility:hidden;
}

span {
  position: absolute;
  white-space:nowrap; /* no needed for path (content) without any spaces*/
  right: 0;
  top: 0;
}
<div id="pathdiv">
  <span></span>
</div>

这是另一种使用 flex 且不添加 span 的方法:

document.querySelector("#pathdiv").innerHTML = "very/very/very-long/path/to/file"
#pathdiv {
  width: 100px;
  overflow: hidden;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  white-space: nowrap;
  height: 20px;
}
<div id="pathdiv">
</div>

于 2017-12-21T13:46:04.843 回答