【问题标题】:How do I resize a div automatically to the size of its contents when the contents of the div have changed?当 div 的内容发生变化时,如何自动将 div 的大小调整为其内容的大小?
【发布时间】:2009-11-17 14:42:25
【问题描述】:

目前,我有这个 DIV,其注册表单位于页面中心。 DIV 的内容来自 ascx 页面。这做得很好。 现在,如果用户尝试填写一个不唯一的名称,一些 jQuery 会在用户名字段旁边添加一条错误消息。这打破了 DIV 的布局,因为现在的内容比以前更宽了。 所以我用谷歌搜索了这个,但我找不到解决方案。

谁能帮我找到一个很好的方法来做到这一点(伪 HTML/js):

<div id="myCenteredDiv" onChangeContents="resizeToNewSize()">
  <!-- div contents -->
</div>

<script type="text/javascript">
  function resizeToNewSize() {
    $("#myCenteredDiv").animateToSize($("#myCenteredDiv").contentWidth, 
      $("#myCenteredDiv").contentHeight);
  }
</script>

我正在寻找“onChangeContents”方法(和/或事件)和“div.contentWidth”属性。

非常感谢您帮助我!

更新:试图更清楚地解释问题

假设我有这个 DIV:

<div id="myDiv">
  <form ...>
    Enter your name: <input id="txtYourName" type="text" name="YourName" value="" />
    <span id="errorYourName"></span>
    <input type="submit" ... />
  </form>
</div>

假设我有这个 jQuery 的 sn-p:

$(document).ready(function() {
  $("#txtYourName").live("blur", function() {
    if (validateInput($("#txtYourName").val())) {
      $("#errorYourName").html("");
      // entry 1
    } else {
      // entry 2
      $("#errorYourName").html("This name is not valid.");
    }
  });
});

...其中validateInput(value) 返回true 以获得有效值。

现在好了。 SimpleModal 插件获取 div 并将其放置在页面的中心,具有一定的宽度和高度,它以某种方式从 div 的内容中读取。所以 div 不会比输入框宽,因为 span 目前是空的。

当输入框失去焦点时,会在 span 中放入一条错误消息。这会破坏 div 的布局。

我可以将代码放入entry 1 中,当错误消息被清除后,用动画将 div 的大小重新调整为某种大小,然后将代码放入entry 2 中,将 div 的大小调整为更大的大小,以便错误消息适合.

但我最想要的是一种方法来判断 div 中的内容是否已更改,并相应地以动画方式自动适应 div。

有什么想法吗?再次感谢。

【问题讨论】:

  • 你试过设置css mid-width属性而不是width属性吗?
  • 这个 div 是否被另一个固定宽度的 div 包围?
  • DIV 的样式如何?是否使用固定尺寸?
  • 我正在使用 SimpleModal jQuery 插件。不确定它是否使用固定的 div,但我可以很好地使用 animate() 调整它的大小。

标签: javascript jquery dom resize


【解决方案1】:

jquery:

$(document).ready(function() {

var originalFontSize = 12;

var sectionWidth = $('#sidebar').width();



$('#sidebar span').each(function(){

    var spanWidth = $(this).width();

    var newFontSize = (sectionWidth/spanWidth) * originalFontSize;

    $(this).css({"font-size" : newFontSize, "line-height" : newFontSize/1.2 + "px"});

});

});

</script>

div:

<div id="sidebar">

<span>fits the width of the parent</span><br />

<span>Hello</span><br />

<span>my</span><br />

<span>name</span><br />

<span>is</span><br />

<span>john</span><br />

<span>1</span><br />

<span>23</span><br />

<span>456</span><br />

<span>12345678910</span><br />

<span>the font size in the span adjusts to the width</span><br />

</id>

预览 http://jbdes.net/dev/js/fontsize.html

【讨论】:

    【解决方案2】:

    我从未使用过 SimpleModal,但从他们网站上的示例看来,您可以设置容器 CSS。如果你想调整高度,尝试将高度设置为auto

    $("#sample").modal({
      containerCss:{
        backgroundColor:"#fff",
        borderColor:"#0063dc",
        height:450,
        padding:0,
        width:830
      }
    });
    

    虽然示例中没有,但我认为您需要在引号中的高度和宽度之后添加px(例如"450px")。


    好的,这是另一个想法。也许这太多了,但添加一个隐藏的输入字段:

    <div id="myDiv">
      <form ...>
        Enter your name: <input id="txtYourName" type="text" name="YourName" value="" />
        <span id="errorYourName"></span>
        <input type="submit" ... />
        <input id="updated" type="hidden" />
      </form>
    </div>
    

    然后附加一个在您更新错误消息的同时触发的更改事件。

    $(document).ready(function() {
      $("#txtYourName").live("blur", function() {
        if (validateInput($("#txtYourName").val())) {
          $("#errorYourName").html("");
          // entry 1
        } else {
          // entry 2
          $("#errorYourName").html("This name is not valid.");
          $("#updated").trigger('change');
        }
      });
      $("#updated").change(function(){
        // resize the modal window & reposition it
      })
    });
    

    这是未经测试的,它可能会过火,但我在 SimpleModal 中没有看到更新功能。


    更新:抱歉,我发现现场活动不支持模糊。所以我做了一些进一步的测试并提出了一个工作演示。我在this pastebin 中发布了它(忽略底部包含的 simpleModal 代码)。这是基本代码

    CSS

    #myDiv { line-Height: 25px; }
    #simplemodal-container { background-color:#444; border:8px solid #777; padding: 12px; }
    .simplemodal-wrap { overflow: hidden !important; }
    .error { color: #f00; display: none; }
    input { float: right; }
    

    HTML

    <div id="myDiv">
      <form>
        What is your name: <input id="txtYourName" type="text" name="YourName" value="" /><br>
        <div id="errorYourName" class="error">This name isn't Arthur.</div>
    
        What is your quest: <input id="txtYourQuest" type="text" name="YourQuest" value="" /><br>
        <div id="errorYourQuest" class="error">This quest must be for the Grail.</div>
    
        What is your favorite color: <input id="txtYourColor" type="text" name="YourColor" value="" /><br>
        <div id="errorYourColor" class="error">Sorry, you must like red or blue.</div>
    
        What is the air speed velocity of an unladen swallow:<br>
        Type:
        <select>
         <option>African</option>
         <option>European</option>
        </select>
        <input id="txtYourGuess" type="text" name="YourGuess" value="" /><br>
        <div id="errorYourGuess" class="error">This guess stinks.</div>
        <hr>
        <input id="submitMe" type="submit" />
      </form>
    </div>
    

    脚本

    $(document).ready(function(){
      $("#myDiv").modal({
       containerCss:{
        height: '165px',
        width: '350px'
       }
     })
     $("#txtYourName").focus();
    
     addValidate('#txtYourName','Arthur','#errorYourName');
     addValidate('#txtYourQuest','Grail|grail','#errorYourQuest');
     addValidate('#txtYourColor','red|blue','#errorYourColor');
     addValidate('#txtYourGuess','11|24','#errorYourGuess'); // See http://www.style.org/unladenswallow/ ;)
    
      $("#myDiv form").change(function() {
       // This is called if there are any changes to the form... added here for an example
       // alert('Form change detected');
      });
    })
    
    function addValidate(el,valid,err){
     $(el).blur(function() {
      if ( $(el).val().length > 0 && !$(el).val().match(valid) ) {
       if ($(err).is(':hidden')) {
        $('#simplemodal-container').animate({'height': ($('#simplemodal-container').height() + 25) + 'px'},1000);
        $(err).slideDown(1000);
       }
      } else {
       // entry 2
       if ($(err).is(':visible')) {
        $('#simplemodal-container').animate({'height': ($('#simplemodal-container').height() - 25) + 'px'},1000);
        $(err).slideUp(1000);
       }
      }
     });
    }
    

    【讨论】:

    • 我会试一试。谢谢!我会检查我的结果。
    • 可惜,它不起作用。它只会使边框变为蓝色,并且 div 非常大(Firebug 告诉我“自动”未定义......)。我将更新问题,并尝试更清楚地说明我想要什么。不过还是谢谢。
    • 希望问题现在更清楚了。 保持手指交叉
    • 好的。所以 SimpleModal 计算 div 的高度/宽度,并将这些值作为硬值放在 element.style 中(例如“宽度:366.5”)。我现在所做的就是在我的 css 文件中放入“width: auto !important”。调整内容大小时,div 不会破坏布局。剩下两件事要做:(1)​​动画调整大小,(2)在页面上居中 div ......(为什么“中心:水平”不是 CSS 标准的一部分?:-))
    • 我知道你所说的居中是什么意思,但是模态窗口有一个固定的位置,所以你不能使用像margin: auto 这样简单的东西。那么为什么将宽度设置为自动而不是高度,高度不是造成问题吗? height: auto !important。是否需要动画化?
    【解决方案3】:

    老式桌子(仍然)非常擅长将事物居中,快速、流畅且无需代码。

    <table width=100% height=100%><tr><td align=center valign=center>
        <table><tr><td style="yourStyle">
            your Content
        </td></tr></table>
    </td></tr></tabĺe>
    
    CSS: HTML,BODY {height:100%; width:100%}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      相关资源
      最近更新 更多