现在的位置: 首页 > 综合 > 正文

自动适应输入内容宽度的TextBox控件

2012年12月01日 ⁄ 综合 ⁄ 共 6802字 ⁄ 字号 评论关闭

    在ASP.NET的上面,TextBox是表单设计时最常用的控件之一。很多时候为了页面的紧凑和美观,我们需要适当的限制TextBox的显示宽度,但是如果TextBox过于窄了之后,又会给用户的填写带了不便,而且更麻烦的是很多时候我们并不知道用户到底会往那个TextBox里填多少内容。为了解决这些问题,下面给大家推荐一个可自动适应输入内容的宽度的TextBox控件。

    本控件是从TextBox控件继承,设计原理是使用一个agent input(type=text)来做为实际的用户录入的TextBox,在焦点切换的过程中完成background input和agent input的属性同步。 

    下面的代码完成两个input之间的样式和属性同步:

function ATB_SwitchToInputAgent(input) 

    注意:不能使用style=style或for( attribute in style)的方式来赋值,否这引起onpropertychange的死循环递归

    第二个问题是使用onpropertychange属性来同步agent input的宽度和其内容宽度相等,代码如下: 

function ATB_AutoIncreaseWidth(input) 

    
if ( input.style.display == 'none' ) return
    
var spanWrapper = input.parentElement; 
    
var userInput = spanWrapper.firstChild; 
    userInput.value 
= input.value; 
    
var absOffsetWidth = GetAbsoluteOffsetLeft(input); 
    
var docClientWidth = window.document.body.clientWidth; 
    
if ( input.scrollWidth < userInput.clientWidth ) 
    { 
        
if ( absOffsetWidth + styleWidth >= docClientWidth )  
        { 
            input.style.width 
= docClientWidth - absOffsetWidth; 
        } 
        
else 
        { 
            input.style.width 
= userInput.clientWidth+2
        } 
        
return
    } 
    
var styleWidth = parseInt(input.style.width); 
    
if ( styleWidth != input.scrollWidth+2 ) 
    { 
        
if ( absOffsetWidth + styleWidth >= docClientWidth )  
        { 
            input.style.width 
= docClientWidth - absOffsetWidth; 
        } 
        
else 
        { 
            input.style.width 
= input.scrollWidth+2
        } 
    } 

    这里需要注意的是当增长的agent input的最右端超出了IE的body区域时,需要停止其增长,否则用户看不见输入的东西了。 

    演示效果如下:

    
*

附 AdjustableTextBox 控件源码

抱歉!评论已关闭.