gpt4 book ai didi

javascript - 将元素宽度设置为元素宽度百分比宽度在页面加载时不正确

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:10 27 4
gpt4 key购买 nike

我试图将一个元素的宽度设置为等于另一个元素的宽度。
问题在于,当第二个元素具有百分比宽度时,jQuery 的 .width() 函数在页面首次加载时返回不正确的宽度

如果我在页面加载后执行相同的操作(例如在 onclick 函数中),则 .width() 会返回元素的正确大小。
刚好是页面第一次加载的时候,好像css还没有根据百分比计算完实际元素的宽度。

这是一些代码:

CSS:

#first {
width:50%;
}

Javascript:

$(function(){
function resizeResults() {
$("#results").css("width", $("#first").width());
}
resizeResults();
});

因此,这不会返回 #results 元素的正确大小。如果我通过 onclick 方法调用此函数,它会将其设置为适当的宽度。

JavaScript/jQuery 应该在执行代码之前考虑加载的 css 百分比,对吗?

最佳答案

你必须改变这个:

function resizeResults() {
$("#results").css("width", $("#first").width());
}

为此:

function resizeResults() {
$("#results").css("width", $("#first").width() + 'px');
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<style>
div {
height: 100px;
background-color: #acacac;
margin: 10px;
}
</style>
<script>
$(function ()
{
function resizeResults()
{
$("#results").css("width", $("#first").width() + 'px');
}
resizeResults();
});
</script>
</head>
<body>
<div id="first" style="width:200px;">Div first</div>
<div id="results" style="width:400px">Div result</div>
</body>
</html>

关于javascript - 将元素宽度设置为元素宽度百分比宽度在页面加载时不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com