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

标签 javascript

我希望根据图像尺寸将图像放置在 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/

相关文章:

php - 如何从js文件中获取值?

javascript - 给定一个对象数组,找到具有特定键的对象

javascript - 淡出页面背景并播放动画

javascript - 带有上一个下一个部分图像的全宽轮播 slider

Javascript 谷歌地图 api 在单独的文件中时不起作用

javascript - 在 Jade filej 中显示来自 Node.js Express 应用程序的变量

javascript - 选择非空选项后默认选项消失

javascript - 单击 jQuery 按钮内的 span

javascript - 带有 setTimeout 的 Jquery 效果

javascript - 我可以在没有 Ender 的情况下将 qwery 与 bean 一起使用吗?