css 禁用的文本区域丢失换行符

rxztt3cl  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(142)

我有一个文本区域与white-space: wrap;
但是,当文本区域被禁用时,换行符将被忽略:

const textarea = document.querySelector("textarea");

document.querySelector("button").addEventListener("click", (e) => {
  if (!textarea.hasAttribute("disabled")) {
    textarea.setAttribute("disabled", "disabled");
  } else {
    textarea.removeAttribute("disabled", "disabled");
  }
});
textarea,
textarea:disabled {
  width: 600px;
  height: 100px;
  white-space: wrap;
}
<textarea wrap="on">1asdfasdf

2afdasdfafdasdfafdasdfaw

3asdfasdf

4asdfasdf</textarea>

<br/>

<button>Toggle 'disabled'</button>

JSFiddle
我希望textarea的内容保持不变,无论是否禁用。它还包括textarea的scrollHeight。
这可能吗?

3df52oht

3df52oht1#

wrap值对于white-space CSS属性无效,可接受的值可以是以下值之一:

white-space: normal|nowrap|pre|pre-line|pre-wrap|initial|inherit;

字符串
要解决这个问题,可以使用white-space: pre-wrap;

textarea:disabled {
  ...
  white-space: pre-wrap;
}


这将确保textarea的内容在行尾换行,并保留白色空格和换行符,即使在禁用textarea时也是如此。
最终版本应该是这样的:

const textarea = document.querySelector("textarea");

document.querySelector("button").addEventListener("click", (e) => {
  if (!textarea.hasAttribute("disabled")) {
    textarea.setAttribute("disabled", "disabled");
  } else {
    textarea.removeAttribute("disabled", "disabled");
  }
});

x

textarea,
textarea:disabled {
  width: 600px;
  height: 100px;
  white-space: pre-wrap;
}
<textarea wrap="on">1asdfasdf

2afdasdfafdasdfafdasdfaw

3asdfasdf

4asdfasdf</textarea>

<br/>

<button>Toggle 'disabled'</button>

的一种或多种

pre vs pre-wrap vs pre-line

*white-space: pre;
***空白保留:**所有的空白序列(如空格和制表符)都严格按照HTML中的编写方式保留。
***换行符:**仅在HTML源代码中的换行符(\n)或<br>元素处换行。当文本超出容器宽度时,它不会自动换行到下一行。
***用例:**通常用于显示代码或预格式化的文本,其中格式至关重要,并且应该完全按照HTML中的格式显示。
*white-space: pre-wrap;
***空白保留:**与pre类似,保留所有序列的空白。
***换行符:**在<br>元素处换行,并在到达容器(行框)末尾时自动换行。
***使用案例:**当您想要保留原始的白色空格和换行符,但还需要文本在其容器中换行时,例如在某些文本编辑器或评论部分中,此功能非常有用。
*white-space: pre-line;
***空格折叠:**与prepre-wrap不同,pre-line将一系列空格折叠成一个空格,但仍保留内容中的换行符。
***断行:**在换行符、<br>元素处断行,在容器边缘换行。
***使用案例:**当您希望保持文本格式的整洁,同时尊重显式的换行符时,这很有用,例如在某些类型的格式化内容显示中。

toe95027

toe950272#

你需要white-space: pre-line

const textarea = document.querySelector("textarea");

document.querySelector("button").addEventListener("click", (e) => {
  if (!textarea.hasAttribute("disabled")) {
    textarea.setAttribute("disabled", "disabled");
  } else {
    textarea.removeAttribute("disabled", "disabled");
  }
});
textarea,
textarea:disabled {
  width: 600px;
  height: 100px;
  white-space: pre-line
}
<textarea wrap="on">1asdfasdf

2afdasdfafdasdfafdasdfaw

3asdfasdf

4asdfasdf</textarea>

<br/>

<button>Toggle 'disabled'</button>

相关问题