如何根据图像尺寸将图像放在<div>中?</div>

时间:2012-11-06 16:11:13

标签: javascript

我希望将图像放在div中,具体取决于图像的尺寸。例如:

  • Div1:任何宽度为&gt;的图片600就到了。
  • Div2:任何高度> 800的图像都会显示在此处。

  • img1尺寸=宽度:601px;身高:300px;将此图像放在上面 DIV1。

  • img2尺寸=宽度:400px;身高: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
        }

    }    
}

由于

3 个答案:

答案 0 :(得分:2)

您的代码示例存在许多问题和疑问,因此很难指出从哪里开始以及要更改的内容。但是我会给你一个关于你的代码如何工作的例子,我希望它有所帮助:

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
}

答案 1 :(得分:0)

好的,如果图像符合条件,请将图像标记添加到字符串的末尾...

var div1Cont = "";
if(imageUrl[i].width>600){
    div1Cont += imgUrl[i];
}

然后在for语句之后,将该字符串放在div中。

document.getElementById("Div1").innerHTML = div1Cont;

然后与你的div 2类似。

答案 2 :(得分:0)

很高兴看到你在没有jquery或任何其他插件的情况下尝试自己做事。你是男人!

首先,我应该说对于每个图像元素,您应该等到加载图像以找出该元素的维度。我认为你应该在javascript中处理"onload"事件。只要图像完全加载,它就会触发。如果您有静态维度,则应通过每个"width"元素的"height"属性中的"style""img"属性设置它们。

获得所有维度后,我相信您的代码似乎没问题,您应该使用"appendChild"方法将"img"元素附加到"div"元素。

干杯

相关问题