1

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
        }
    }); 
});
4

1 に答える 1

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%;
}

例 JSFiddle

于 2013-10-30T10:36:48.823 に答える