2013-05-31 73 views
0

我通過滾輪創建圖像縮放,但在函數之間傳遞變量時遇到問題。可變範圍和事件觸發的匿名函數

在我致電img_scroll()函數之前,我需要獲取要放大和縮小圖像的最小和最大尺寸。獲取我需要等待圖像首先加載的尺寸。

所以現在我等待圖像加載,調用尺寸函數,然後一旦加載尺寸,我調用滾動函數。但現在,我無法將鏈中的變量傳遞給滾動函數。

zoom = 0.01; 

$(document).ready(function(){ 
    $("#img_wrapper").imagesLoaded(function(){ 

     getImgSizes(); 

    }); 


}); 

function getMinImgSize() { 
    if ($("#img_wrapper img").width() <= $("#img_wrapper img").height()) { 
     $("#img_wrapper img").css("width", "100%"); 
    } else { 
     $("#img_wrapper img").css("height", "100%"); 
    } 
    min_width = $("#img_wrapper img").width(); 
    min_height = $("#img_wrapper img").height(); 
    return {height: min_height, width: min_width}; 
} 

function getImgSizes() { 
    var newImg = new Image(); 
    var width, height; 
    imgSrc = $("#img_wrapper img")[0].src; 

    minDimensions = getMinImgSize(); 

    newImg.onload = function(minDimensions) { //incorect way to pass varaible to anonymous function 
     originalHeight = newImg.height; 
     originalWidth = newImg.width; 
     maxDimensions = {height: originalHeight, width: originalWidth}; 
     img_scroll(minDimensions, maxDimensions); 
    } 

    newImg.src = imgSrc; // this must be done AFTER setting onload 

} 

function img_scroll(minDimensions, maxDimensions){ 
    var minDimensions = minDimensions; 
    var maxDimensions = maxDimensions; 
    $('#img_wrapper').mousewheel(function(event, delta, deltaX, deltaY) { 
     console.log(delta, deltaX, deltaY); 
     if (deltaY < 0) { 
      if ($("#img_wrapper img").width < maxDimensions.width) { 
       $("#img_wrapper img").width($("#img_wrapper img").width()*(1+zoom)); 
       $("#img_wrapper img").height($("#img_wrapper img").height()*(1+zoom)); 
      } else { 
            $("#img_wrapper img").width(maxDimensions.width); 
            $("#img_wrapper img").height(maxDimensions.height); 
           } 
     } else { 
      if ($("#img_wrapper img").width > minDimensions.width) { 
       $("#img_wrapper img").width($("#img_wrapper img").width()*(1-zoom)); 
       $("#img_wrapper img").height($("#img_wrapper img").height()*(1-zoom)); 
      } else { 
          $("#img_wrapper img").width(minDimensions.width); 
          $("#img_wrapper img").height(minDimensions.height); 
         } 
     } 
    }); 
} 

如何通過最小&最大尺寸變量環比下滑任何幫助將是巨大的。

回答

1

通過對JavaScript的方式closures工作,minDimensions是提供給您的匿名函數沒有被明確地傳遞這應該工作:

function getImgSizes() { 
    var newImg = new Image(); 
    var width, height; 
    var imgSrc = $("#img_wrapper img")[0].src; 

    var minDimensions = getMinImgSize(); 

    newImg.onload = function() { 
     var originalHeight = newImg.height; 
     var originalWidth = newImg.width; 
     var maxDimensions = {height: originalHeight, width: originalWidth}; 
     img_scroll(minDimensions, maxDimensions); 
    } 

    newImg.src = imgSrc; // this must be done AFTER setting onload 

} 

編輯:使用var防止全局變量。