2

私はいくつかの画像座標を持っています、そして私はそれらを使ってjavascriptを持つものに小さな画像を置きたいです。これはjavascriptで実行できますか、それともdivを作成してそのcss属性を変更する必要がありますか?ちなみに、画像はページのどこにでも配置できます。

4

3 に答える 3

1

完全に機能するコードは次のとおりです。ライブデモ

CSS

.overlays{
    position:absolute;
}

JS

function showImage() {
    // myImage : ID of image on which to place new image

    var image = document.getElementById('myImage');

    console.log(image.width);

    margin = 20;

    l = image.offsetLeft;
    t = image.offsetTop;
    w = image.width;
    h = image.height;

    // Location inside the image
    offX = parseInt(Math.random() * w);
    offY = parseInt(Math.random() * h);

    if(offX > margin) offX -= margin;
    if(offY > margin) offY -= margin;

    l += offX;
    t += offY;

    var newImage = document.createElement("img");
    newImage.setAttribute('src', '1.jpg');
    newImage.setAttribute('class', 'overlays');
    newImage.style.left = l + "px";
    newImage.style.top = t + "px";
    document.body.appendChild(newImage);
}
于 2013-01-04T13:18:04.107 に答える
1

これを試して、新しい画像を(X,Y)親画像の座標に配置します。

var newImg = document.getElementById('newImg'), // your new (small) image
    img = document.getElementById('parentImg'); // parent image
document.body.insertBefore(newImg, img); // Insert the new image before the image
document.body.insertBefore(img, newImg); // Then switch places (So the small image is after the big one in the DOM)

newImg.style.position = 'relative';
newImg.style.left = X + "px";
newImg.style.top = (Y - img.height)+"px"; // Substract the height of the source image to get the position relative to the top left.

ダブルinsertBeforeは、最初に大きな画像の前に挿入し、次に大きな画像をその前に移動することによって、入札画像の後に新しい画像を挿入することです。
次に、大きな画像を基準にして新しい画像の座標を設定するだけです。

実例(違いを示すために2秒後にオーバーレイを表示するように設定)

于 2013-01-04T13:20:12.627 に答える
0

css:

#yourId{
    position: absolute;
}

js:

var img = document.getElementById('yourId'), // or any other selector
    x = x, // your data
    y = y; // your data
img.style.left = x+"px";
img.style.top = y+"px";
于 2013-01-04T13:11:36.423 に答える