开发者

get css() property before append()?

how can you get a css property before the element is appended?

css

input.inp {
    padding:3px 2px 3px 2px;
}

js

var elm = $('<input class="inp" typ开发者_StackOverflow中文版e="text" />');

alert(elm.css('padding-left'));
td.append(elm);
alert(elm.css('padding-left'));

only the second alert retuns the value...

I want the input element to have width:100%.. but since you can't do that (when the input has a padding of its own) I need to set the width in pixels

  1. get width of the the TD where the INPUT has to be appended...
  2. get the left and right padding of the INPUT
  3. append the INPUT to the TD with the width of the TD minus the left and right padding of the INPUT


If it's not in the DOM, then you can't, AFAIK.


Probably because the padding is in a style sheet, and it depends on the position in the document which css applies to the element. So when the element is not in place, it doesn't have that styles yet. It has to be part of the DOM at least, and (depending on the css selectors) the exact position in the DOM may matter too.


You could insert a hidden input, with the class, get the css properties and the use them.

<input id="getPadding" class="inp" type="text" style="display:none" />

Then after the element is appended You can just get the elements parent width and then set the input to that width minus the amount of padding.. Like so

 $('td input').width($(this).parent().width() - [$('#getPadding').css('padding-left') + $('#getPadding').css('padding-right')])

Alternatively there is a css only solution but it does not work in IE7 and below

td input {
    margin: 0px;
    width: 100%;
    height: 100%;
    border: 0px;
    display: block;
    padding: 2px 5px;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
} 


When you do:

$('<input class="inp" type="text" />');

Is the same as doing:

var input = document.createElement("input");
input.type = "text";
input.className = "inp"; 

And in both these cases they return a Detached element.

As the element hasn't been appended to the DOM yet the class doesn't take affect so the no Css is applied to the element.

So when you try to get the padding it won't be set.

You would have to add the padding inline to able to get it before you add it to the DOM

$('<input class="inp" type="text" />').css("padding", "5px");


var padbefore = $("elmid").css('padding-left');
alert(padbefore);
$("td").append('elmid');
var paddafter = $("elmid").css('padding-left');
alert(paddafter);   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜