javascript计算有时不会发生 [英] javascript calculation sometimes not happening

查看:70
本文介绍了javascript计算有时不会发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码段中:

var scr_h = $(document).height();
var scr_w = $(document).width();
var logo = {                                                             
    width   :   (scr_w*.25),                                              
    img     :   document.createElement('img'),                           
    src     :   'images/static/mk_vc.png'                                
};  
$(logo.img).attr('src', logo.src);                                       
$('#logo').append(logo.img);                                             
$('#logo').css({                                                         
    'margin-top'    :   scr_h*.15+'px',                                       
    'width'         :   logo.width+'px',
    'left'          :   (scr_w/2)-(logo.width/2)+'px' //this doesn't always work...
}); 
alert($('#logo').css('left'));        

有时,警报会以自动"(而不是正确的数字)返回.如果刷新页面,通常会发生这种情况(尽管按ctrl + refresh通常可以解决此问题).我尝试通过php渲染页面并将?randomnumber=$randomnumber参数附加到JavaScript调用,但这没有帮助,这意味着它不是某种缓存问题.

Sometimes the alert comes back with "auto" instead of the correct number. It usually happens if the page is refreshed (though a ctrl+refresh will usually fix the issue). I tried rendering the page via php and attaching a ?randomnumber=$randomnumber parameter to the JavaScript call, but it didn't help, which means it's not a caching issue of some sort.

它似乎也出现在所有浏览器中.我的客户使用的是Mac,并且已经尝试使用Chrome和Safari,而我使用的是Linux,并且已经在Chrome和Firefox中进行了尝试.

It also seems to happen in all browsers. My client has a Mac, and has tried with Chrome and Safari, and I have Linux and have tried it in Chrome and Firefox.

有什么想法吗?其余JavaScript功能均正常运行,无论该特定行是否正确呈现. margin-topwidth css也始终起作用.似乎只有left会引起问题.

Any thoughts at all? The rest of the JavaScript functions fine, regardless as to whether that particular line renders properly. The margin-top and width css also always functions. It appears to be only the left that gives issues.

我尝试更改先渲染"left"的顺序,但这也无济于事,尽管其他两个属性仍然很好.

I tried changing the order to render "left" first, but that also did not help, though the other two attributes were still just fine.

完整脚本可以在 http://meenakhalili.turnleftllc.com上看到/scripts/js/dev/mk.js ,网址为meenakhalili.turnleftllc.com.尝试刷新几次.您会发现问题所在.

The full script can be seen at http://meenakhalili.turnleftllc.com/scripts/js/dev/mk.js, with the site at meenakhalili.turnleftllc.com. Try refreshing a few times. You'll see the problem.

推荐答案

Chchrist昨晚在评论中回答了这个问题.将计算设置为在映像的onload事件解决后才进行.

Chchrist answered this question last night in the comments. Setting the calculation to occur after the onload event of the image fixed the problem.

我现在要发布此信息,但希望在此归因!

I'm posting this for now, but would love to give credit where it's due!

这篇关于javascript计算有时不会发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆