2011-02-07 26 views
1

在IE自動寬度,上聚焦欲潛在擴大到width: auto元素的寬度僅在自動寬度較寬然後我已設置靜態寬度。我試圖避免的只是總是將元素設置爲width: auto並使元素縮小。我只希望它在必要時擴大。查找元件的與jquery/JS

任何人有一個乾淨的方式來檢查當設置爲自動具有了先設置該屬性的元素的寬度會是什麼?現在,我設置了它,然後檢查寬度並將其設置回靜態,似乎應該有一個更清晰的解決方案。使用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')); 
     } 
    } 

回答

1

不知道你會發現一個清晰的解決方案,但這裏有一個不涉及操縱元素本身:

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

謝謝安德魯 - 希望我錯過了一個標準的屬性或方法 - 但我確實喜歡編輯一個克隆元素而不是原始元素來獲取寬度的想法。 – kmfk 2011-02-08 16:00:42