开发者

How to check if css property is set?

As per the title really.

If notice that if I check $(elem).css('margin-top') it returns 0px even though I haven't explicitly set this style, either inline or in a stylesheet.

Basically I am setting the marg开发者_开发百科in each time I hover over an element (to vertically align some content) so would rather just do this once.

I can't set the alignment on page load because the elements are hidden (display:none) so it needs to be done at the time they are displayed.


if(!$(elem).data('hasSetMargin')){
    $(elem).css('margin-top', someValue);
    $(elem).data('hasSetMargin', true);
}


What's the problem with setting it several times?

It looks like you're trying to early-optimize your code.


It's not easy to tell because there are many sources which affect the value of a style such as margin-top.

However, you don't need to tell really because:

  1. Setting it more than once should do no harm in your case.
  2. You can improve your code by adding/removing/toggling HTML classes (addClass/removeClass/toggleClass) and styling the elements with pure static CSS (using class selectors) instead of setting the styles yourself. This has the added benefit of making your code readable.

Regarding the readability -- what would you rather read? This:

function() {
    $(selector).css('margin-top', '10px').css('border', '2px red solid');
}

or this:

function() {
    $(selector).addClass('update-pending');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜