我编码了这个:
$(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
结果。但这是容器的宽度,而不是文本元素的宽度。
尝试使用
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>
$(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>