我正在尝试制作一个 textarea
,它占用标题 div
之后的所有剩余空间。
要求:
- 标题的高度取决于内容。
- Textarea 必须占据标题后的所有剩余高度。
- 如果textarea内容过多,会出现滚动条。
基本上,我正在努力实现这一目标:http://jsfiddle.net/hLd7jc9x/ , 但没有 % 的高度(因为标题的高度必须根据内容而变化,而不是固定的 %)。同理,textarea 也不能用fixed
或absolute
定位。我知道这很容易用 div
实现,但我不知道如何用 textarea
来实现。
这是我目前的情况:http://jsfiddle.net/t5862grv/1/
最佳答案
我修改了你的fiddle .
主要解决方案是使用 flexbox .考虑到不支持 flexbox,我们使用 modernizr用于检测,并添加一些自定义的基于 jquery 的高度更新逻辑(支持窗口大小调整)。考虑到 js 被关闭(这些天很少见),我们回到你的旧 fiddle 的基于百分比的高度样式。
CSS:
* { margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
#a { background: #F00; }
#b { background: #0F0; resize: none; }
/* Don't forget to use Autoprefixer or similar, so you cover all the necessary vendor prefixes based on your browser requirements. */
.flexbox body { display: flex; flex-direction: column; }
.flexbox #a { flex: 0 0 auto; }
.flexbox #b { flex: 0 1 100%; }
/* When browser doesn't support flex, i.e. IE9, use the old, less flexible styling. This can also be replaced with a JS script to manually resize the textarea height. In fact, the custom height setting is set to only be a backup if js isn't allowed. */
.no-flexbox #b { width: 100%; }
.no-js.no-flexbox #a { height: 10%; }
.no-js.no-flexbox #b { height: 90%; }
JS:
$(function(){
// Guard.
if (!Modernizr.flexbox) {
return;
}
// Define.
var $container = $('body');
var $header = $('#a');
var $textarea = $('#b');
function updateTextArea() {
var height = $container.innerHeight() - $header.outerHeight();
$textarea.height(height);
}
var requestAnimationFrame = (
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.oRequestAnimationFrame
);
// Run.
updateTextArea();
$(window).resize(function(){
requestAnimationFrame(updateTextArea);
});
})
关于html - 占用标题后所有剩余空间的文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465116/