Script working only on page reload

你。 提交于 2019-12-29 08:22:34

问题


I'm using jQuery to align images on an horizontal view website, but the script only works when I reload the page.

http://joliannelm.steveforest.com/edition/roux-de-service.html

The script is called just before

This is the script :

$(document).ready(function() {

    var width = 0;

    $('#page img').each(function() {
        width += $(this).outerWidth(true);
    });

    $('#page').css('width', width + 50);

});

Once the page is reloaded it's OK, but if you clear the cache, it's back...

Someone knows why?? Thanks.


回答1:


This is probably a timing problem: The ready event is fired when the DOM is ready - this can be before the images are loaded. Because you're not giving the images fixed width attributes, you need them to be loaded before you can tell their width.

This is where the load event is the most appropriate trigger.

$(window).load(function() {  ... your code here

unlike ready, load will wait for all associated files - images, style sheets, JavaScript files etc.



来源:https://stackoverflow.com/questions/3969144/script-working-only-on-page-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!