我有一个以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