自动调整通过 renderUI 创建的 textAreaInput

Auto-resize textAreaInput created through renderUI

我正在尝试调整 textAreaInput 的大小,以便它们默认显示整个区域的内容。在此之后,,我可以使用在 ui 下创建的 textAreaInput(例如,textAreaInput 适当调整大小)。当创建 textAreaInput 作为 renderUI 的一部分时,我无法让它工作(如 textAreaInput 不调整大小),更不用说作为模块的一部分了。如果有帮助,我很乐意使用 shinyjs

这里的根本问题是我不明白Javascript。


在这两种情况下,使用:

jc <- "document.addEventListener('DOMContentLoaded', function(event) {
    var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init () {
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change',  resize);
observe(text, 'cut',     delayedResize);
observe(text, 'paste',   delayedResize);
observe(text, 'drop',    delayedResize);
observe(text, 'keydown', delayedResize);

text.focus();
text.select();
resize();
};init()
})
"

这与在 ui 下创建的 textAreaInput 将根据输入或粘贴调整大小:

library(shiny)

ui <- fluidPage(
  shiny::tags$script(jc),
  textAreaInput(inputId = "text", label = "a", value = "b")
  # uiOutput("tai")
)

server <- function(input, output, session) {

  # output$tai <- renderUI({
  #     textAreaInput(inputId = "text", label = "a", value = "b")
  # })
}

shinyApp(ui, server)

虽然在服务器端 renderUI 中创建的 textAreaInput 不会自动调整大小:

library(shiny)

ui <- fluidPage(
  shiny::tags$script(jc),
  # textAreaInput(inputId = "text", label = "a", value = "b")
  uiOutput("tai")
)

server <- function(input, output, session) {

  output$tai <- renderUI({
      textAreaInput(inputId = "text", label = "a", value = "b")
  })
}

shinyApp(ui, server)

您可以通过将 init() 替换为 setTimeout(function(){init();}, 500); 来包括延迟:

jc <- "document.addEventListener('DOMContentLoaded', function(event) {
  var observe;
  if (window.attachEvent) {
    observe = function (element, event, handler) {
      element.attachEvent('on'+event, handler);
    };
  } else {
    observe = function (element, event, handler) {
      element.addEventListener(event, handler, false);
    };
  }
  function init () {
    var text = document.getElementById('text');
    function resize () {
      text.style.height = 'auto';
      text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
      window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
  };
  setTimeout(function(){init();}, 500);
})
"