2013-10-08 21 views
1

我想在文本框的按鍵事件上對齊頁面中心的文本框,但我只能用下面給出的代碼放大文本框的大小...在按鍵事件的頁面中間對齊文本框

<title></title> 

<script type="text/javascript"> 

    function resize(selectObj) { 

     selectObj.style.height = '400px'; 

     selectObj.style.width = '800px'; 

     selectObj.style.padding = '10px 10px 10px 10px'; 

     selectObj.style.position = 'absolute'; 

    } 
</script> 

<body> 

    <form id="form1" runat="server"> 

    <div> 

    <asp:TextBox ID="txt" runat="server" TextMode="MultiLine" onkeypress="resize(this);"> 
</asp:TextBox> 

    </div> 

    </form> 

</body> 

</html> 
+0

您需要設置保證金-left和margin-right屬性使其居中。 –

回答

0

這將幫助你肯定

$("#txt").keypress(function() { 
    $(this).css({ 
     'position': 'absolute', 
     'left': ($(window).width()/2 - $(this).width()/2) + 'px', 
     'top': ($(window).height()/2 - $(this).height()/2) + 'px', 
    }); 
1

你可以像下面這樣做

$("#txt").keypress(function() { 
$("#maindiv").css({'display' : 'block', 'text-align' : 'center'}); 
}); 

Demo Fiddle

更新爲中心屏幕

$("#txt").keypress(function() { 
$(this).css('margin-left', ($(window).width()/2)); 
}); 

Demo Fiddle Center of screen

+0

我沒有看到OP用JQuery標記了問題 – Satpal

+0

@Satpal會將其更改爲javascript – Rex

+0

它工作正常,但我希望文本框以按鍵爲中心 –

1

您可以使用絕對定位居中的。你應該考慮的文本框的寬度和高度:

$("#txt").keypress(function() { 
    $(this).css({ 
     'position': 'absolute', 
     'left': ($(window).width()/2 - $(this).width()/2) + 'px', 
     'top': ($(window).height()/2 - $(this).height()/2) + 'px', 
    }); 
0
$("#txt").keypress(function() { 
$(this).css({ 
    'position': 'absolute', 
    'left': ($(window).width()/2 - $(this).width()/2) + 'px', 
    'top': ($(window).height()/2 - $(this).height()/2) + 'px', 
});