【问题标题】:auto resizing textarea in a modal在模态中自动调整文本区域的大小
【发布时间】:2016-11-04 10:49:47
【问题描述】:

我正在使用 Bootstrap 和 jQuery 创建一个 ASP.NET 网页。

我最近实现了一个显示日志的模式。单击链接时会显示模态:

<a data-toggle="modal" data-target="#logData">Open</a>

<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Log for @Html.DisplayFor(model => model.Alias)</h4>
            </div>
            <div class="modal-body">
                <textarea class="form-control log" rows="5" placeholder="Log is empty.">@Html.DisplayFor(model => model.Log)</textarea>    
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

模态框包含一个不会自动调整大小的文本区域。

我找到了以下代码:

$('textarea').each(function () {
    this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
    this.style.height = 'auto';
    this.style.height = (this.scrollHeight) + 'px';
});

这应该使我的文本区域能够自动调整大小,并且它可以在我的代码中的其他地方工作,但在上面的这个模式中不起作用。至少在输入文本区域时不会,但在打开模式时它似乎会自动调整大小。

有人知道为什么吗?最终如何解决?

谢谢!

【问题讨论】:

  • 第一次渲染页面时是否存在模态的html,或者是否使用ajax动态加载(在这种情况下您需要事件委托)?
  • 它是部分视图的一部分,在单击表格行时正在绘制。实际上,您昨天帮助我的那段代码。所以我想我需要某种事件委托?
  • @StephenMuecke 我读了这个learn.jquery.com/events/event-delegation,但我似乎真的不知道如何用我的代码实现事件委托
  • $(document).on('input', 'textarea', function() { ... } 但为了获得最佳性能,请将 document 替换为页面首次呈现时存在的 textarea 的最近祖先
  • 您不能使用第二个 sn-p,因为事件是在页面第一次呈现时附加的,此时 textarea 还不存在。对于第一个 sn-p,如果在第一次呈现页面时存在 &lt;p&gt; 元素,那么最好给它一个 id 属性,以便您可以使用 &lt;p id="xx"&gt;$('#xx').on('input', 'textarea', function() { ... } - 这只是意味着&lt;p&gt; 元素将侦听其中任何 input 元素的任何 &lt;textarea&gt; 事件

标签: javascript jquery html asp.net-mvc twitter-bootstrap


【解决方案1】:

您可以使用此代码,如果 textarea 未隐藏(例如,在尚未显示的模式中),该代码将起作用

let setHeight = (input) => {

    input.style.overflow = 'hidden';
    input.style.height = 0;

    input.style.height = `${ input.scrollHeight + 2 }px`;

};

$('textarea').on('input, keyup', function () {
    setHeight(this);
})

对于引导模式,你可以这样做:

$('.modal').on('shown.bs.modal', function () {
    $(this).find('textarea').each(function () {
        setHeight(this);
    });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2019-08-22
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多