【问题标题】:How do I place an image inside a <div> depending on the image dimensions?如何根据图像尺寸将图像放置在 <div> 内?
【发布时间】:2012-11-06 16:11:13
【问题描述】:

我希望根据图像尺寸将图像放置在 div 中。例如:

  • Div1:任何宽度 > 600 的图像都放在这里。
  • Div2:任何高度 >800 的图像都放在这里。

  • img1 尺寸 = 宽度:601px;高度:300px;把这张图片放在 第 1 部分。

  • img2 尺寸 = 宽度:400 像素;高度:850px;把这张图片放在里面 第 2 部分。

我怎样才能使用 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
        }

    }    
}

谢谢

【问题讨论】:

  • 你在问你的 if 语句里面放什么吗?

标签: javascript


【解决方案1】:

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

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
}

【讨论】:

    【解决方案2】:

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

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

    然后在 for 语句之后,将该字符串放入您的 div..

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

    然后与您的 div 2 类似。

    【讨论】:

      【解决方案3】:

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

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

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

      干杯

      【讨论】:

        猜你喜欢
        • 2015-08-28
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-23
        • 2011-06-15
        • 1970-01-01
        相关资源
        最近更新 更多