因爲這不能用簡單的HTML/CSS操作來完成,所以唯一的選擇就是JavaScript來根據圖像大小重新計算座標。爲此我已經把一個函數(雖然有涉及到兩個函數)達到這一目的:
function findSizes(el, src) {
if (!el || !src) {
return false;
}
else {
var wGCS = window.getComputedStyle,
pI = parseInt,
dimensions = {};
dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
var newImg = document.createElement('img');
newImg.src = src;
newImg.style.position = 'absolute';
newImg.style.left = '-10000px';
document.body.appendChild(newImg);
dimensions.originalWidth = newImg.width;
document.body.removeChild(newImg);
return dimensions;
}
}
function remap(imgElem) {
if (!imgElem) {
return false;
}
else {
var mapName = imgElem
.getAttribute('usemap')
.substring(1),
map = document.getElementsByName(mapName)[0],
areas = map.getElementsByTagName('area'),
imgSrc = imgElem.src,
sizes = findSizes(imgElem, imgSrc),
currentWidth = sizes.actualWidth,
originalWidth = sizes.originalWidth,
multiplier = currentWidth/originalWidth,
newCoords;
for (var i = 0, len = areas.length; i < len; i++) {
newCoords = areas[i]
.getAttribute('coords')
.replace(/(\d+)/g,function(a){
return Math.round(a * multiplier);
});
areas[i].setAttribute('coords',newCoords);
}
}
}
var imgElement = document.getElementsByTagName('img')[0];
remap(imgElement);
JS Fiddle demo。
請注意,這需要一個實現window.getComputedStyle()
(最新的瀏覽器,但僅限於版本9以上的IE)的瀏覽器。此外,除了確保將所需的參數傳遞給函數之外,沒有任何理智檢查。但是,如果你想嘗試,這應該是一個開始。
參考文獻:
圖像已定義尺寸,爲什麼使用百分比?假設你沒有拉伸圖像來填充屏幕(這被認爲是不好的做法)。 – 2012-07-06 13:59:07
我的圖片肯定會延伸到適合整個窗口瀏覽器。如果你仔細管理你的圖片(例如使用媒體查詢或其他技術提供不同的版本),那麼這不是一個壞習慣。 – 2012-07-06 14:06:19
好吧,如果您爲每個屏幕尺寸分配不同的圖像,則應該可以使用地圖「區域」的固定尺寸。請參閱@ Baszz的答案。 – 2012-07-06 14:29:39