如何获取“overflow-x: auto;”内元素的全宽地区?

问题描述 投票:0回答:2

我编码了这个:

$(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>

我想计算

#text
元素内部的
#container
元素的宽度。目前,它向我显示了
300px
结果。但这是容器的宽度,而不是文本元素的宽度。

javascript jquery css overflow horizontal-scrolling
2个回答
1
投票

尝试使用

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>


0
投票

$(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>
开始

© www.soinside.com 2019 - 2024. All rights reserved.