javascript:WAITING代码中使用的图像加载

标签 javascript

我在使用 javascript 创建图像轮播时遇到了无法修复的问题。我使用 jcarousel 进行一些“hacky”修改,以允许具有不同宽度的图像(纵向/横向) 最终结果是我正在使用一些如下所示的代码

function mycarousel_itemAddCallback(carousel, first, last, dir)
{
    var thumbdir = 'gallery/' + dir + '/thumbs/' //set the thumbs dir
    var fulldir = 'gallery/' + dir + '/full/' //set the full images dir
    for (i = 0; i < 21; i++) {
        var no = i+1; //number image we are on
        var img = new Image(); //make a new image
        img.src = thumbdir + no + '.jpg'; //set its source
        var fullimg = fulldir + no + '.jpg'; //set full omages source as well
        var html = mycarousel_getItemHTML(img.src, fullimg, img.width); //make some html for the image, with width
        carousel.add(i+1, html, img.width); //add the image to the carousel, with width passed in
        tagID = 'jcarousel-item-' + no; //get the css tag of the image just added
        changeStyle(tagID, img.width); // force its height in inline css to prevent bugs
    }

现在本质上,问题似乎是“img.width”最终为0,因为图像尚未加载。这意味着图库中的所有图像最终宽度均为 0,因此不可见。刷新页面(因此所有图像都已在缓存中),一切正常,“img.width”值正确。

在设置图像加载警报后强制暂停可以使 img.width 成为正确的值,但显然这是一个可怕的解决方法。 任何人都可以建议一种方法,允许 javascript 加载图像,并在继续脚本之前获得正确的大小?

提前感谢所有帮助

最佳答案

使用 onload 事件,如下所示:

var img = new Image();
img.onload = function(){
  // image has been loaded
};

// proper way to assign any src right now
img.src = 'path there';

alert(img.width);

关于javascript:WAITING代码中使用的图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462561/

相关文章:

javascript - JavaScript 数组中的对象插入问题

javascript - angularjs中的依赖错误

javascript - 使用 AngularJS 将图像上传到 Imgur

javascript - 根据产品标题添加图片

javascript - ReactJS多输入问题setState和state

javascript - GraphQL 数组/列表变量?

javascript - Vue 将数据传递给 POST 方法

javascript - 使用 TAB 编辑 DT 表上的下一个单元格

javascript - 捆绑和缩小导致 Angular 错误 : $injector:unpr unknown provider

php - 图像不闪烁