2011-09-10 27 views
3

截至https://developer.mozilla.org/en/Determining_the_dimensions_of_elements說:scrollWidth/scrollHeight屬性給出的尺寸無效

如果您需要了解的內容的實際大小,無論 多的是怎麼回事當前可見,您需要使用scrollWidth和 scrollHeight屬性。

因此,我使用scrollWidth和scrollHeight屬性將元素調整爲其實際大小(jsfiddle)。

HTML:

<textarea>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad brrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</textarea> 

的JavaScript:

(function ($) { 
    $(document).ready(function() { 
     $('textarea').css({ 
      width: $('textarea')[0].scrollWidth, 
      height: $('textarea')[0].scrollHeight 
     }); 
    }); 
})(jQuery); 

我會假設,如果我設定的尺寸爲內容的實際大小,元素就沒有滾動條爲它的尺寸將是大足以讓內容不會溢出。對?因此,它應該是你這個圖像中看到的樣子:

IE

但它不能正常工作i.stack.imgur.com/lKxoz.png,你可以從下面的圖片看:i.stack.imgur.com/JXt0e.png

:i.stack.imgur.com/emGyG.png

歌劇:i.stack.imgur.com/7MAX5.png

我的問題是scrollWidth和scrollHeight屬性有什麼問題?他們給我無效的尺寸!

回答

1

我覺得你把它非常複雜! 有一個scrollHeightscrollWidth屬性,它等於可滾動元素內部的寬度和高度。因此,將該元素的heightwidth設置爲scrollWidthscrollHeight即可解決該問題。

var textarea = document.getElementsByTagName('textarea')[0]; 
textarea.style.height = textarea.scrollHeight + 'px'; 
textarea.style.width = texyarea.scrollWidth + 'px'; 

fiddle here

+0

不好意思,你說「非常複雜」是什麼意思?它仍然不能在你的jsfiddle中正常工作。以下是你在Chrome i.stack.imgur.com/9Iqh0.png中的工作方式,以下是你如何在Opera中使用i.stack.imgur.com/9aTT8.png – Jack

+0

你想「調整元素的實際大小」做...你想要什麼呢? – Mohsen

+0

其實它沒有。看看我發佈的截圖。你的建議代碼與我的代碼是一樣的,除了你的不使用jQuery(我認爲這就是你的意思是「非常複雜」,是不是?),你的錯誤類型,只是供參考:它應該是「textarea」而不是「texyarea」。 – Jack

6

的問題是,你不包括滾動條的大小。嘗試設置「溢出」爲「隱藏」或添加滾動條的大小,它的工作原理。有很多方法可以計算出這個大小,谷歌會幫助你。出於測試目的,請在Windows和17px上使用Chrome。
根據您使用此片段的上下文,您可能需要在內容更改時重置大小。你也應該給textarea一個固定的寬度,否則瀏覽器會分配任何感覺。

(function ($) { 
    $(document).ready(function() { 
     $('textarea').css({ 
      width: $('textarea')[0].scrollWidth+'px', 
      height: $('textarea')[0].scrollHeight+'px', 
      overflow: 'hidden' 
     }); 
    }); 
})(jQuery);