2013-10-29 34 views
1

如何调整基于所述调整后的图像的比例的顶部/左/宽度/高度,使用jquery如何调整基于所述调整后的图像的比例的顶部/左/宽度/高度,使用jquery

我试图

$(window).bind('resize', function() { 
    reposition(); 

    var maxWidth = $(window).width(); // Max width for the image 
    var maxHeight = $(window).height(); // Max height for the image 

    var ratio = 0; // Used for aspect ratio 
    var width = $(this).width(); // Current image width 
    var height = $(this).height(); // Current image height 
      /
    $('.hotspot').each(function() { 

     // Check if the current width is larger than the max 
     if (width > maxWidth) { 
      ratio = maxWidth/width; // get ratio for scaling image 
      $(this).css("width", maxWidth); // Set new width 
      $(this).css("height", height * ratio); // Scale height based on ratio 
      height = height * ratio; // Reset height to match scaled image 
      width = width * ratio; // Reset width to match scaled image 
     } 

     // Check if current height is larger than max 
     if (height > maxHeight) { 
      ratio = maxHeight/height; // get ratio for scaling image 
      $(this).css("height", maxHeight); // Set new height 
      $(this).css("width", width * ratio); // Scale width based on ratio 
      width = width * ratio; // Reset width to match scaled image 
      height = height * ratio; // Reset height to match scaled image 
     } 
    }); 
}); 
+0

...以及它是如何工作的出来吗? – Moob

+0

我在图像上有一些热点(链接占位符)。当我最小化窗口时,它们不会缩小 –

+0

对不起,我不知道'图像上的占位符'是什么意思。你可以做一个[JSFiddle](http://jsfiddle.net)来说明问题。 – Moob

回答

1

你可以使用CSS这和你的所有“热点”的大小和位置的百分比。

HTML

<div id="imageWithHotspots"> 
    <img src="http://placehold.it/400x200&text=hotspots+here+and+here" /> 
    <a href="#" class="hotspotA" title="Hotspot A"></a> 
    <a href="#" class="hotspotB" title="Hotspot B"></a> 
</div> 

CSS

html, body {margin:0;width:100%; height:100%;} 
#imageWithHotspots {width:100%; height:50%;position:relative;} 
#imageWithHotspots img {width:100%; height:100%;} 
#imageWithHotspots a { 
    background:rgba(20,100,100,.5); 
    display:block; 
    position:absolute; 
} 
#imageWithHotspots a:hover { 
    background:rgba(200,100,10,.5); 
} 
#imageWithHotspots .hotspotA { 
    top:48%; 
    left:45.2%; 
    height:6.6%; 
    width:8.5%; 
} 
#imageWithHotspots .hotspotB { 
    top:48%; 
    left:62%; 
    height:6.6%; 
    width:8.5%; 
} 

Example JSFiddle

相关问题