简体   繁体   English

如何使用JQuery / CSS在div中垂直对齐按钮?

[英]How to align button by vertically in div using JQuery/CSS?

There is the following code: 有以下代码:

HTML: HTML:

<table>
    <tr>
        <td class="first_column">Sign in</td>
        <td class="second_column">->(1)</td>
        <td class="third_column"><div class="translated">Some text</div></td>
    </tr>
</table>

JS: JS:

$(".translated").mouseenter(function(){
    if ($(this).hasClass("editable")){
        return;
    }
    var h=$(this).height();
    var w=$(this).width();
    $(this).empty();
    var field = $("<input/>", {
            type: "text",
            value:$(this).text()
        }).appendTo(this);
    var button = $("<button></button>").appendTo(this);
    field.height(h - field.outerHeight()+field.height());
    button.height(h-button.outerHeight()+button.height());
    $(this).height(h);
    $(this).width(w);
    $(this).addClass("editable");
});

CSS: CSS:

.translated
{
    color:green;
    font-weight:bold;
    vertical-align:middle;
    width:100%;
}

This code addes input and button items to div container when mouse focuses the div. 当鼠标将div对准div时,此代码将输入和按钮项添加到div容器中。 But there is the following problem - button has got a good height, but incorrect align. 但是存在以下问题-按钮的高度合适,但是对齐不正确。 I need that a new button item is in center of row by vertically. 我需要一个新的按钮项垂直位于行的中心。 Please, tell me, how can I do it? 请告诉我,我该怎么办?

You have to set button width in your js code: 您必须在js代码中设置按钮宽度:

button.css('width', field.width());

try on this fiddle: http://jsfiddle.net/velthune/NCrUu/5/ 试试这个小提琴: http : //jsfiddle.net/velthune/NCrUu/5/

I cleaned up your code, added a table row and set the width of input and button. 我清理了代码,添加了表格行,并设置了输入和按钮的宽度。 They are different because of the margins and paddings browsers give these elements 它们的不同之处在于浏览器为这些元素提供了空白和边距

http://jsfiddle.net/andreaslyngstad/BFwU7/ http://jsfiddle.net/andreaslyngstad/BFwU7/

HTML 的HTML

<table>
            <tr>
                <td class="first_column">Sign in</td>
                <td class="second_column">->(1)</td>
                <td class="third_column">
                  <div class="translated">Some text</div>
                </td>
            </tr>
<tr>
                <td class="first_column"></td>
                <td class="second_column"></td>
                <td class="third_column" id="button_container"></td>
            </tr>
 </table>​​​

CSS 的CSS

table{
    width:100%
}
button{
    width:100px
}
input{
    width:96px
}
.translated {
    color:green;
    font-weight:bold;
    vertical-align:middle;
    width:100%;
  }​

JS JS

var field = $("<input/>", {
    type: "text",
    value: $(this).text()
})
var button = $("<button>sign in</button>")

$(".translated").mouseenter(function() {
    $(this).empty();
    field.appendTo(this);
    button.appendTo($("#button_container"));
});​

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

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