1

画像のサイズに応じて、div 内に画像を配置しようとしています。例えば:

  • Div1: 幅が 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
        }

    }    
}

ありがとう

4

3 に答える 3

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
}
于 2012-11-06T16:20:07.850 に答える
0

画像が基準を満たしている場合は、画像タグを文字列の末尾に追加します...

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

for ステートメントの後に、その文字列を div. 内に配置します。

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

そして、div 2 と同様です。

于 2012-11-06T16:18:29.240 に答える
0

jquery やその他のプラグインを使用せずに、自分で何かをしようとしているのを見るのは良いことです。あなたは男です!

まず第一に、すべての画像要素について、画像が読み込まれるまで待って、その要素のサイズを確認する必要があります。"onload"イベントは JavaScript で処理する必要があると思います。画像が完全に読み込まれるたびに起動します。静的なディメンションがある場合は、各要素の属性でそれら"width""height"プロパティを設定する必要があります。"style""img"

すべてのディメンションを取得した後、コードは問題ないように見え、メソッドを使用して要素を要素"appendChild"に追加する必要があると思います。"img""div"

乾杯

于 2012-11-06T16:18:57.893 に答える