簡體   English   中英

如何在“overflow-x: auto;”中獲取元素的全寬區域?

[英]How to get full width of an element inside an "overflow-x: auto;" area?

我編碼了這個:

 $(document).ready(function() { $("button").click(function() { alert("Width of #text: " + $("#text").width()); }); });
 * { margin: 0; padding: 0; font-family: sans-serif; } #container { width: 300px; height: 150px; background-color: grey; position: relative; } #scroll-area { overflow-x: auto; height: 100%; } #text { white-space: nowrap; }
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <div id="container"> <div id="scroll-area"> <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div> </div> </div> <button>Get width of #text</button>

我想計算#container元素內的#text元素的寬度。 目前,結果顯示300px 但那是容器的寬度,而不是文本元素的寬度。

嘗試使用scrollWidth功能

 $(document).ready(function() { $("button").click(function() { alert("Width of #text: " + $("#scroll-area")[0].scrollWidth); }); });
 * { margin: 0; padding: 0; font-family: sans-serif; } #container { width: 300px; height: 150px; background-color: grey; position: relative; } #scroll-area { overflow-x: auto; height: 100%; } #text { white-space: nowrap; }
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <div id="container"> <div id="scroll-area"> <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div> </div> </div> <button>Get width of #text</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM