【问题标题】:offsetHeight not working properly in chromeoffsetHeight 在 chrome 中无法正常工作
【发布时间】:2012-06-02 19:29:13
【问题描述】:

我遇到了一个有趣的问题。我不知道可能是什么原因。我试图在互联网上搜索,但没有得到解决方案。问题是 offsetWidth 在 Chrome 中运行良好,但 offsetHeight 无法正常运行。有时它会返回值,但有时不会。请问有什么办法可以解决这个问题。

注意:我尝试过使用 id.height、id.clientHeight。但所有人都给我同样的问题。在我的项目中,我们也使用 Prototype 和 JQuery。

我也使用了原型 getHeight().. 但在 Chrome 中不起作用。 getWidth() 工作完美。但所有这些都在 Firefox 中运行良好...... :(

这是代码块

$('leftImage_<?php echo $iExtLoop; ?>').style.position="relative";
$('leftImage_<?php echo $iExtLoop; ?>').style.left= ($('leftImageDiv').offsetWidth - $('leftImage_<?php echo $iExtLoop; ?>').offsetWidth)/2 + "px";
$('leftImage_<?php echo $iExtLoop; ?>').style.top= ($('leftImageDiv').offsetHeight - $('leftImage_<?php echo $iExtLoop; ?>').offsetHeight)/2 + "px";

if($('stripLeft_<?php echo $iExtLoop; ?>')){
    $('stripLeft_<?php echo $iExtLoop; ?>').style.position="relative";
    $('stripLeft_<?php echo $iExtLoop; ?>').style.left= ($('leftImageDiv').offsetWidth - $('stripLeft_<?php echo $iExtLoop; ?>').offsetWidth) + "px";
    $('stripLeft_<?php echo $iExtLoop; ?>').style.top= ($('leftImageDiv').offsetHeight - $('stripLeft_<?php echo $iExtLoop; ?>').offsetHeight) + "px";                                      
}

重构的代码,由 Šime Vidas 添加:

var img = $( 'leftImage_<?php echo $iExtLoop; ?>' );
var div = $( 'leftImageDiv' );
var strip = $( 'stripLeft_<?php echo $iExtLoop; ?>' );

img.style.position = "relative";
img.style.left = ( div.offsetWidth - img.offsetWidth ) / 2 + "px";
img.style.top = ( div.offsetHeight - img.offsetHeight ) / 2 + "px";

if ( strip ) {
    strip.style.position = "relative";
    strip.style.left = ( div.offsetWidth - strip.offsetWidth ) + "px";
    strip.style.top= ( div.offsetHeight - strip.offsetHeight ) + "px";
}

【问题讨论】:

  • 添加了代码块...有什么想法吗??
  • $ 是什么?原型还是 jQuery?
  • @FaizulHasan 要大声喊叫,请缓存这些引用。我已将改进后的代码添加到您的问题中...
  • "有时它返回值但有时不返回。"
  • 在您的代码中,您正在阅读三个不同元素的offsetHeight。三个值都不正确吗?

标签: javascript google-chrome height


【解决方案1】:

由于至少有一个元素似乎是 IMG 元素,我猜测该元素在执行代码时尚未完成加载。

图像必须单独检索(由浏览器),因此您必须确保仅在完成加载后才读取它们的高度。

【讨论】:

  • 抱歉造成混淆。 onload 在某种意义上不起作用,正确计算了图像的宽度和高度。但它的风格并没有被设定为那个形象。这意味着:strip.style.position = "relative"; strip.style.left = ( div.offsetWidth - strip.offsetWidth ) + "px"; strip.style.top= ( div.offsetHeight - strip.offsetHeight ) + "px";这部分代码块没有被执行或者什么的。但图像未定位到所需位置
  • @FaizulHasan 在该行设置断点并查看它是否执行。如果是,请查看分配了哪些值。
猜你喜欢
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 2015-04-04
  • 1970-01-01
  • 2014-07-22
  • 2018-12-31
  • 2015-11-14
相关资源
最近更新 更多