代码之家  ›  专栏  ›  技术社区  ›  Mike

jquery:javascript不做我告诉它的事情

  •  1
  • Mike  · 技术社区  · 15 年前

    我知道标题非常微妙,但我完全不知道该如何命名这个问题,也不知道这个函数到底发生了什么。

    function update_background(source, isSystem){
        if (!isSystem) {
            source.replace(/\/tn_/, '');
            jQuery('div#drag_container img[alt="background"]').attr('src', source); //*1
            jQuery('div#drag_container img[alt="background"]').attr('style', '');
            var height = jQuery('div#drag_container img[alt="background"]').height();
            var width = jQuery('div#drag_container img[alt="background"]').width();
            var ratio = Storyboard['format'];
            //Don't touch the paddings, they are correct!
            if (height * ratio > width) {
                var padding = (Storyboard['display'] - (width * (Storyboard['height'] / height))) / 2;
                jQuery('div#drag_container img[alt="background"]').css({
                    'height': Storyboard['height'],
                    'padding-left': padding
                });
            } else {
                var padding = (Storyboard['height'] - (height * (Storyboard['display'] / width))) / 2;
                jQuery('div#drag_container img[alt="background"]').css({
                    'width': Storyboard['display'],
                    'padding-top': padding,
                    'padding-bottom': padding
                });
            }
        } else {
            jQuery('div#drag_container img[alt="background"]').attr('src', source).attr('style', '');
            jQuery('div#drag_container img[alt="background"]').css({
                'width': Storyboard['display'],
                'height': Storyboard['height']
            });
        }
    }
    

    这个函数应该做的是,拍照,获取它的大小,将它与显示它的容器的大小进行比较,调整它的大小,使其尽可能大而不突出容器,最后,在需要的地方应用填充以使图像居中。不管图片是横向的还是纵向的,函数都知道该做什么。图片被缓存,这样我们就不会得到错误的值(我已经有了这样的错误)。如果是系统背景,我们不关心大小和填充是否正确。完美工作3个月。

    最近,它的行为相当奇怪。在注释行处 *1 它不仅重置了img标记的src属性,而且还设置了高度和填充,就像它已经在填充计算中一样。它们在下一行中再次被删除(实际上并不是为了这个目的而插入的,而是为了获得图片的原始尺寸),它仍然有效。

    当然,除非让函数以常规速度运行,否则它不会重置样式。我对这个虫子很恼火,因为我不知道从哪里开始搜索。

    函数只被调用一次。它只在函数中运行一次。它不包含在事件中,并且在两个完全不同的位置调用此函数。

    有什么想法吗?

    编辑1

    我发现每个浏览器都不会出现这个错误。

    • 雪豹系统
      • 火狐:行为描述
      • 歌剧院:都错了,但我们公司不支持
      • Safari:仍然完美无瑕
    • 视窗XP
      • Chrome:与Safari相同
      • 火狐:行为描述
      • IE8:相同行为
      • IE7: 实际工作!
    • Linux
      • 火狐:行为描述
      • konkeror:甚至不能使用我的javascript
    1 回复  |  直到 15 年前
        1
  •  3
  •   JasonWyatt    15 年前

    您可能在获取图像的大小时遇到问题,因为无法保证在检查图像的尺寸时它已被加载。

    var $img = jQuery('div#drag_container img[alt="background"]');
    $img.bind('load', function(){
        // do all of your stuff with the width and the height of the image in here...
        var width = $(this).width();
        var height = $(this).height();
    });
    $img.attr('src', source);  /* kicks off the loading of the image, the bound function 
                                * above will get called when it's done.
                                */