【问题标题】:Textarea that takes all remaining space after header标题后占用所有剩余空间的文本区域
【发布时间】:2023-03-29 11:50:02
【问题描述】:

我正在尝试创建一个 textarea 来占用标题 div 之后的所有剩余空间。

要求:

  • 标题的高度取决于内容。
  • Textarea 必须占据页眉之后的所有剩余高度。
  • 如果textarea内容过多,会出现滚动条。

基本上,我正在尝试实现这一点:http://jsfiddle.net/hLd7jc9x/,但没有 % 的高度(因为标题的高度必须根据内容而变化,而不是固定的 %)。同理,textarea 也不能用fixedabsolute 定位。我知道使用div 很容易实现这一点,但不知何故我不知道如何使用textarea 来实现。

这是我目前的情况:http://jsfiddle.net/t5862grv/1/

【问题讨论】:

    标签: html css height textarea


    【解决方案1】:

    我已经修改了你的fiddle

    主要解决方案是使用flexbox。考虑到不支持 flexbox,我们使用modernizr 进行检测,并添加了一些基于 jquery 的自定义高度更新逻辑(支持窗口大小调整)。考虑到 js 被关闭(现在很少见),我们回到你的老小提琴基于百分比的高度样式。

    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);
        });
    
    })
    

    【讨论】:

    • 感谢您并点赞!我希望有一个 CSS 解决方案,但如果没有这样的解决方案,我会接受你的 JS 解决方案。感谢您的努力!
    • 所以flexbox解决方案是纯css。只有IE9及以下需要切换到js。如果您不需要 IE9 支持,您可以放心地不包含 js 和任何非 flexbox css。
    • 对不起! Herp derp 就我而言 :)
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2012-09-27
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多