我有一個以div顯示的圖像列表。 div的寬度會有所不同,因爲它們被指定爲其容器的百分比。其目標是獲得靈活的設計。在呈現之前使用javascript設置樣式
圖像比它們包含的div寬,但所有圖像的寬度不一樣。我想通過在圖像上設置一個負邊界來改變圖像,並以這種方式將圖像置於其容器中。
由於負邊距取決於圖像的寬度,所以我需要在設置邊距之前檢查寬度。
function marginsOfImages() {
var images = document.getElementsByTagName('img');
for (i = 0; i < images.length; i++) {
var parent = images[i].parentNode;
var parentWidth = window.getComputedStyle(parent, null).getPropertyValue("width");
/*In order to remove the "px" from the style: */
var indexOfPx = parentWidth.search("px");
parentWidth = parseInt(parentWidth.substring(0, indexOfPx));
var imageWidth = window.getComputedStyle(images[i], null).getPropertyValue("width");
indexOfPx = imageWidth.search("px");
imageWidth = parseInt(imageWidth.substring(0, indexOfPx));
var value = parentWidth + 90; //Want to shift the image 90px to the left
if (imageWidth > value) {
images[i].style.marginLeft = (value * (-1)).toString() + "px";
}
}
}
window.onload = marginsOfImages;
的問題是,圖像是在第一無任何餘量呈現,再經過第二或所以它們將根據當JavaScript的已完成它們的寬度得到的餘量;在頁面顯然已經加載之後,圖像的外觀將會改變。
如何在顯示任何圖像之前設置正確的邊距?我需要在確定尺寸之前加載所有圖像,對不對?
在此先感謝!
是有一個原因你不使用像jQuery的JavaScript庫? – 2012-07-16 15:19:41
我本來可以使用jQuery,可能有這樣一些整潔的代碼。我只是新來的,所以認爲在這種情況下使用javascript更容易。 – Timothy 2012-07-18 10:33:47