当div的内容发生变化时,如何自动调整div的大小? [英] How do I resize a div automatically to the size of its contents when the contents of the div have changed?

查看:102
本文介绍了当div的内容发生变化时,如何自动调整div的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个以页面为中心的注册表单的DIV。 DIV的内容来自一个ascx页面。这很好。
现在,如果用户尝试填写不唯一的名称,则会在用户名字段旁边的一些jQuery添加错误消息。这破坏了DIV的布局,因为内容现在比以前更广泛。
所以我已经google了我的方式,但我找不到这个解决方案。



任何人都可以帮助我找到一个很好的方式来做这个(伪HTML / js):

 < div id =myCenteredDivonChangeContents =resizeToNewSize()> 
<! - div内容 - >
< / div>

< script type =text / javascript>
函数resizeToNewSize(){
$(#myCenteredDiv)。animateToSize($(#myCenteredDiv)。contentWidth,
$(#myCenteredDiv)。contentHeight)
}
< / script>

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



非常感谢帮助我!



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



假设我有这个DIV:

 < div id =myDiv> 
< form ...>
输入您的姓名:< input id =txtYourNametype =textname =YourNamevalue =/>
< span id =errorYourName>< / span>
< input type =submit... />
< / form>
< / div>

让我们来看看这个jQuery的代码片段:


$ b $ ($($)$($)$($)$($)$($)$($) if(validateInput($(#txtYourName)。val())){
$(#errorYourName)。html();
// entry 1
} else {
// entry 2
$(#errorYourName)。html(此名称无效);
}
});
} );

...其中 validateInput(value)返回 true 作为有效值。



现在好了。 SimpleModal插件采用div并将其放置在页面上,具有一定的宽度和高度,以某种方式读取div的内容。因此,div不比输入框宽,因为此时的范围是空的。



当输入框失去焦点时,会将错误消息放入跨度。然后打破div的布局。



我可以把代码放入条目1 当出现错误消息已被清除时,将其移动到某种大小的动画,并将代码更改为条目2 ,将div的大小调整为更大的大小,以便错误消息适合。



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



任何想法?再次感谢

解决方案

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

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

虽然这个例子没有,但我想你需要添加 px 在高度和宽度之后的引号(例如450px)。



< hr>

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

 < div id =myDiv> 
< form ...>
输入您的姓名:< input id =txtYourNametype =textname =YourNamevalue =/>
< span id =errorYourName>< / span>
< input type =submit... />
< input id =updatedtype =hidden/>
< / form>
< / div>

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

  $(document).ready(function(){
$(#txtYourName)live(blur function(){
if(validateInput($(#txtYourName)。val())){
$(#errorYourName)。html();
//条目1
} else {
//条目2
$(#errorYourName)。html(此名称无效);
$(#updated ).trigger('change');
}
});
$(#updated)。change(function(){
//调整模态窗口大小&重新定位它
})
});

这是未经测试的,可能会超出,但在SimpleModal中看不到更新功能






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



CSS

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

HTML

 code>< div id =myDiv> 
< form>
你叫什么名字:< input id =txtYourNametype =textname =YourNamevalue =/>< br>
< div id =errorYourNameclass =error>此名称不是Arthur。< / div>

您的任务是什么?< input id =txtYourQuesttype =textname =YourQuestvalue =/>< br>
< div id =errorYourQuestclass =error>此任务必须适用于Grail。< / div>

你最喜欢的颜色是什么:< input id =txtYourColortype =textname =YourColorvalue =/>< br>
< div id =errorYourColorclass =error>抱歉,您必须喜欢红色或蓝色。< / div>

无空气燕子的空气速度是多少?< br>
类型:
< select>
< option>非洲< / option>
< option>欧洲< / option>
< / select>
< input id =txtYourGuesstype =textname =YourGuessvalue =/>< br>
< div id =errorYourGuessclass =error>这个猜测发臭。< / div>
< hr>
< input id =submitMetype =submit/>
< / form>
< / div>

脚本

  $(document).ready(function(){
$(#myDiv)。modal({
containerCss:{
height:'165px',
宽度:'350px'
}
})
$(#txtYourName)。focus();

addValidate('#txtYourName','Arthur ''''''''''''''''''''''''''''''''' errorYourColor');
addValidate('#txtYourGuess','11 | 24','#errorYourGuess'); //参见http://www.style.org/unladenswallow/;)

$(#myDiv form)。change(function(){
//如果表单有任何更改,则调用此示例
// alert( '检测到表单变更');
});
})
function addValidate(el,valid,err){
$(el).blur(function(){
if($(el).val()长度> 0&&$(el).val()。match(valid)){
if($(err).is(':hidden')){
$ '#simplemodal-container')。animate({'height':($('#simplemodal-container')。height()+ 25)+'px'},1000);
$(err)幻灯片(1000);
}
} else {
//条目2
if($(err).is(':visible')){
$ ('#simplemodal-container')。animate({'height':($('#simplemodal-container')。height() - 25)+'px'},1000);
$(err) .slideUp(1000);
}
}
});
}


At the moment, I have this DIV with a registration form centered over the page. The contents of the DIV come from an ascx-page. 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. This breaks the layout of the DIV, since the contents now are wider than they used to be. So I've googled my way into this, but I can't find a solution for this.

Can anyone help me find a nice way to do this (pseudo 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.

Thanks a lot for helping me out!

update: trying to explain the problem more clearly

Let's say I have this 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:

$(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.

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. So the div isn't wider than the input box, since the span is empty at the moment.

When the input box loses focus, an error message is put into the span. This then breaks the layout of the 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.

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.

Any ideas? Thanks again.

解决方案

I've never used SimpleModal, but from the examples on their site it looks like you can set the container CSS. If you want the height to adjust, try setting the height to 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 (e.g. "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.


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). Here is the essential code

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>

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

这篇关于当div的内容发生变化时,如何自动调整div的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆