简体   繁体   English

当div的内容发生变化时,如何自动调整div的大小?

[英]How do I resize a div automatically to the size of its contents when the contents of the div have changed?

At the moment, I have this DIV with a registration form centered over the page. 目前,我有这个DIV,注册表单位于页面中心。 The contents of the DIV come from an ascx-page. DIV的内容来自ascx页面。 This is done nicely. 这很好地完成了。 Now, if the user tries to fill in a name that's not unique, an error message is added by some jQuery next to the username field. 现在,如果用户尝试填写不唯一的名称,则会在username字段旁边添加一些错误消息。 This breaks the layout of the DIV, since the contents now are wider than they used to be. 这打破了DIV的布局,因为现在的内容比以前更宽。 So I've googled my way into this, but I can't find a solution for this. 所以我已经google了我的方式,但我找不到解决方案。

Can anyone help me find a nice way to do this (pseudo HTML/js): 任何人都可以帮我找到一个很好的方法(伪HTML / js):

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

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

I'm looking for the "onChangeContents" method (and/or event) and the "div.contentWidth" property. 我正在寻找“onChangeContents”方法(和/或事件)和“div.contentWidth”属性。

Thanks a lot for helping me out! 非常感谢帮助我!

update: trying to explain the problem more clearly 更新:试图更清楚地解释问题

Let's say I have this DIV: 假设我有这个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>

And let's say I have this snippet of jQuery: 让我们说我有这个jQuery片段:

$(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.");
    }
  });
});

...where validateInput(value) returns true for a valid value. ...其中validateInput(value)为有效值返回true

Well now. 现在好了。 The SimpleModal plugin takes the div and places it centered on the page, with a certain width and height it somehow reads off of the contents of the div. SimpleModal插件获取div并将其置于页面的中心,具有一定的宽度和高度,它以某种方式读取div的内容。 So the div isn't wider than the input box, since the span is empty at the moment. 因此div不比输入框宽,因为此时跨度是空的。

When the input box loses focus, an error message is put into the span. 当输入框失去焦点时,会在范围中输入错误消息。 This then breaks the layout of the div. 然后这打破了div的布局。

I could put code into entry 1 that resizes the div back with an animation to some size when the error message has been cleared, and code into entry 2 that resizes the div to a bigger size so the error message will fit. 我可以将代码放入entry 1 ,当错误消息被清除时,将动画大小调整为div,然后将代码放入entry 2 ,将div的大小调整为更大的大小,以便错误消息适合。

But what I'd like best is a way to tell if the contents within the div have changed, and fit the div accordingly, animated and automatically. 但我最喜欢的是一种方法来判断div中的内容是否已经改变,并相应地适应div,动画和自动。

Any ideas? 有任何想法吗? Thanks again. 再次感谢。

Jquery: 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:

<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>

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

I've never used SimpleModal, but from the examples on their site it looks like you can set the container CSS. 我从未使用过SimpleModal,但是从他们网站上的示例看起来你可以设置容器CSS。 If you want the height to adjust, try setting the height to auto 如果要调整高度,请尝试将高度设置为auto

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

Although the example doesn't have it, I'd think you need to add px after the height and width in quotes (eg "450px" ). 虽然示例没有它,但我认为你需要在引号的高度和宽度之后添加px (例如"450px" )。


Ok here is another idea. 好的,这是另一个想法。 Maybe this is too much, but add a hidden input field: 也许这太多了,但添加一个隐藏的输入字段:

<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>

then attach a change event which is triggered at the same time you update the error message. 然后附加在更新错误消息的同时触发的更改事件。

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

This is untested and it may be going overboard, but I don't see an update function in SimpleModal. 这是未经测试的,它可能会过分,但我没有在SimpleModal中看到更新功能。


Update : Sorry I figured out that blur isn't supported with live event. 更新 :对不起,我发现直播活动不支持模糊。 So I did some further testing and came up with a working demo. 所以我做了一些进一步的测试,并提出了一个工作演示。 I posted it in this pastebin (ignore the included simpleModal code at the bottom). 我把它贴在这个pastebin中 (忽略底部包含的simpleModal代码)。 Here is the essential code 这是基本代码

CSS 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 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>

Script 脚本

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

Old fashioned tables are (still) great at centering things, fast, fluid and code free. 老式桌子(仍然)非常适合居中,快速,流畅且无代码。

<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%}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM