开发者

Find element's automatic width with jquery / js

In IE, on Focus I want to potentially expand the width of an element to width: auto only where the automatic width is wider then the static width I have set. What Im trying to avoid is just always setting the element to width: auto and having the element shrink. I only want it to expand where necessary.

Anyone have a clean way to check what the elements width would be when set to auto 开发者_如何学Cwith out having to first set the attribute? Right now, I set it, then check the width and potentially set it back to static, seems like there should be a cleaner solution.

Example of current code with jquery:

$('mySelector').live('focus', function() {
      //store the original width, then set the element to width: auto
      $(this).data('w', $(this).width()).css('width', 'auto'));
      //is the element now shorter?  if so, set it back to the original width
      if ($(this).width() < $(this).data('w')) {
         $(this).width($(this).data('w'));
      }
   }


Not sure if you will find a cleaner solution, but here's one that doesn't involve manipulating the element itself:

function adjustWidth($el) {
    var $clone = $el.clone().css({width: "auto", display:"none"}).appendTo($el.parent());
    var width = $clone.width();
    $clone.remove();

    if (width > $el.width()) {
        $el.css("width", "auto");
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜