2016-02-26 132 views
1

我有一個div內的3個圖像。我如何動態加載和覆蓋在這三個圖像在div中的一個圖像?加載另一個圖像

我的HTML看起來像這樣

<div id="div1"> 


    <img id="img1" src="images/Green.png" draggable="false" class="tile" ondrop="drop(event)" ondragover="allowDrop(event)"> 
    <img id="img2" src="images/Green.png" draggable="false" class="tile" ondrop="drop(event)" ondragover="allowDrop(event)"> 
    <img id="img3" src="images/Green.png" draggable="false" class="tile" ondrop="drop(event)" ondragover="allowDrop(event)"> 


</div> 

<div id="inner"> 
    <img id="dragRed" src="images/Red.png" draggable="true" ondragstart="drag(event)" width="5%" height="5%"> 
    <img id="dragYellow" src="images/Yellow.png" draggable="true" ondragstart="drag(event)" width="5%" height="5%"> 
    <img id="dragGreen" src="images/Green.png" draggable="true" ondragstart="drag(event)" width="5%" height="5%"> 
</div> 

我使用這個腳本嘗試,但它會導致IMG1消失。

$("#img1").each(function() { 
       var $overlay = $('<div></div>'); 
       $overlay.css({ 
        position: "relative", 
        display: "inline-block", 
        width: $(this).width(), 
        height: $(this).height(), 
        backgroundPosition: "center center", 
        backgroundImage: "url(images/affection.png)" 
       }); 
       $(this).wrap($overlay); 
      }); 
+0

'$(「#img1」)。each'將查找'id'爲'img1'的多個元素。 「身份證」必須是唯一的。由於所有的圖像都有一個'tile'類,你可以通過改變這段代碼來讀取'$(「。tile」)。' – Yass

+0

我實際上只想改變img1 – Jetrica

回答

1

這裏的主要問題是:你想改變的東西,包裝圖片的背景。背景將始終落後。

您需要包含一個與圖像一起生活並覆蓋它的元素。 有了一些細微的變化,我們與div包裹圖片:

<div id="div1"> 
    <div id="img1"> 
     <img src="https://placekitten.com/g/50/50" draggable="false" class="tile" ondrop="drop(event)" ondragover="allowDrop(event)"> 
    </div> 
</div> 

而且JS NOW的外觀爲div,並附加疊加圖像旁邊:

$("#div1 div").each(function() { 
    var $overlay = $('<div class="overlay"></div>'); 
    $overlay.css({ 
    position: "absolute", 
    top: "0", 
    left: "0", 
    display: "inline-block", 
    zIndex: "1", 
    width: $(this).width(), 
    height: $(this).height(), 
    backgroundPosition: "center center", 
    backgroundImage: "url(https://placehold.it/50x50)" 
    }); 
    $(this).append($overlay); 
}); 

這裏是Fiddle link

希望它有幫助!

+0

謝謝,真的有幫助。有沒有一種方法可以將圖像大小縮放到div大小的百分比?您可以使用具有css轉換屬性的'$ .css':https:/(這是).high(),$(this).width(), height:$(this).height(), – Jetrica

+0

/jsfiddle.net/pu2w6rgo/3/ –

相關問題