我希望根据图像尺寸将图像放置在 div 中。例如:
- Div1:宽度 > 600 的所有图像都放在这里。
Div2:所有高度 >800 的图像都放在这里。
img1 尺寸 = 宽度:601 像素;高度:300px;将此图像放在 Div1.
- img2 尺寸 = 宽度:400 像素;高度:850px;将这张图片放在里面 Div2.
我如何使用 javascript 做到这一点?
这是我正在尝试的方式。
#Div1{
width:600px;
height:auto;
}
#Div2{
width:auto;
height:600px;
}
var imageUrl = new Array();
imageUrl[2] = '<img id="checkfunctionfirst" src="img1.jpg">'
imageUrl[3] = '<img id="checkfunctionfirst" src="img2.jpg">'
imageUrl[5] = '<img id="checkfunctionfirst" src="img3.jpg">'
function checkfunctionfirst () {
for(i=0;i<=imageUrl.length;i++){
if(imageUrl[i].width>600){
//place this image on Div1
}
if(imageUrl[i].height>800){
//place this image on Div2
}
}
}
谢谢
最佳答案
您的代码示例存在许多问题,因此很难指出从哪里开始以及要更改什么。但我会给你一个例子,说明你的代码如何工作,我希望它有所帮助:
var imageUrl = ['img1.jpg','img2.jpg','img3.jpg'], // the images to use
i = 0, len = imageUrl.length, img; // some vars used later
for( ; i<len; i++ ) { // loop through the image URLs
img = new Image(); // create a new image
img.onload = function() { // you need this to get the width/height
if ( this.height > 800 ) { // "this" is the Image element
document.getElementById('Div2').appendChild(this); // append to to the div
} else if ( this.width > 600 ) {
document.getElementById('Div1').appendChild(this);
}
};
img.src = imageUrl[i]; // give the Image element a source
}
关于javascript - 如何根据图像尺寸将图像放置在 <div> 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13254970/