在移动设备上重新加载javascript?

在移动设备上重新加载javascript?,javascript,html,Javascript,Html,我有一个脚本,它计算div的高度并将其作为样式返回。但是当你旋转移动设备时,高度会改变,所以我需要一种方法来重新加载它。我怎样才能做到这一点 <script type="text/javascript"> window.onload = function() { var height = document.getElementById('id').offsetHeight; document.getElementById('id').style.marginTop =

我有一个脚本,它计算div的高度并将其作为样式返回。但是当你旋转移动设备时,高度会改变,所以我需要一种方法来重新加载它。我怎样才能做到这一点

<script type="text/javascript">
window.onload = function() {
    var height = document.getElementById('id').offsetHeight;
    document.getElementById('id').style.marginTop = height + 'px';
}
</script>

window.onload=函数(){
var height=document.getElementById('id')。offsetHeight;
document.getElementById('id').style.marginTop=height+'px';
}

从中生成一个函数,并在加载和调整大小时调用该函数。无需重新加载页面,只需再次调用代码:

<script type="text/javascript">
function calcHeight() {
    var height = document.getElementById('id').offsetHeight;
    document.getElementById('id').style.marginTop = height + 'px';
}

window.onload = calcHeight;
window.resize = calcHeight;

</script>

函数calcHeight(){
var height=document.getElementById('id')。offsetHeight;
document.getElementById('id').style.marginTop=height+'px';
}
window.onload=calcHeight;
window.resize=calcHeight;

您可以创建一个函数:

function setHeight() {
   var height = document.getElementById('id').offsetHeight;
   document.getElementById('id').style.marginTop = height + 'px';
}
您可以调用onload:

window.onload = function() {
   setHeight();
   // Other actions when window is loaded
}
和onresize:

window.onresize = function(event) {
   setHeight();
   // Other actions when window is resized
}

这应该可以完成任务。

我看到了对它的描述(至少对Android是这样)。不需要,只需使用窗口大小调整。它可以在
警报(“检测到调整大小事件!”)等情况下工作但不适用于我的脚本。为什么?@nicolas-也许你需要将marginTop重置回它的默认值(就像加载页面时一样),然后才能获得offsetHeight。可能有更好的方法来完成您正在尝试做的事情,但是如果没有看到HTML,我们无法对此提供建议。