如何显示您单击的当前元素的图像?

时间:2015-09-09 20:11:54

标签: javascript jquery html css

我有这个样本:

link

例如,当我点击“.dreapta”中的div元素1来放置图像并点击paragraful项目时,Daca是两个隐藏一个元素所以...

代码HTML:

<ul>

    <li id="#bar">
        <img src="http://theimageconference.org/wp-content/uploads/2014/01/images-50x50.png"width=50 height=50></img>
        <p>ELEMENT 1</p>
    </li>
    <li id="#bar">
        <img src="http://whyfiles.org/wp-content/uploads/2013/04/promega_logo.png" width=50 height=50></img>
        <p>ELEMENT 2</p>
    </li>
    <li id="#bar">
        <img src="http://bikechicago.com/wp-content/uploads/bikechicago-uber-image-C2.png" width=50 height=50></img>
        <p>ELEMENT 3</p>
    </li>
    <li id="#bar">
        <img src="http://coordinate.com.au/wp-content/uploads/2014/06/CBR_Web_Images.jpg" width=50 height=50></img>
        <p>ELEMENT 4</p>
    </li>
    <li id="#bar">
        <img src="http://www.bpifrance-lelab.fr/var/bpi/storage/images/media/images/image-couverture/34625-1-fre-FR/image-couverture_large.jpg" width=50 height=50></img>
        <p>ELEMENT 5</p>
    </li>
    <li id="#bar">
        <img src="http://odpiralnicasi.com/photos/012/539/image-big.jpg" width=50 height=50></img>
        <p>ELEMENT 6</p>
    </li>

</ul>

<div class="dreapta">

</div>

CODE CSS:

ul{
    list-style-type:none;
    width:95px;
    float:left;
}

ul li{border-bottom:1px solid;}

p{padding;0;margin:0;}

.dreapta{float:right;width:100px;height:100px;border:1px solid;}

CODE JS:

$("ul li").click(function (event) {
    var barIndex = $("ul li").index($(this)) + 1;
    alert("Element poistion:" + barIndex);
});

我把图片更好地理解:

enter image description here

你能帮我解决这个问题吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

您可以使用clone()方法来实现它。方法如下:

$("ul li").click(function (event) {
    var barIndex = $("ul li").index($(this));
    alert("Element poistion:" + barIndex);
    $(".dreapta").html('');
    $("ul li").eq(barIndex).find('img').clone().css({
        'width': '100px',
        'height': '100px' 
    }).appendTo('.dreapta');
});

这是更新的小提琴: https://jsfiddle.net/rtcydtyh/12/

答案 1 :(得分:0)

每次点击图片时,前一张图片都会被删除,新图片会出现。

css也采用了样式,因此图像将采用完整的div(高度和宽度)。

代码:

   var img;
$("ul li").click(function (event) {

    if (img !=undefined){
       $(img).remove();
    }
    var barIndex = $("ul li").index($(this)) + 1;
    alert("Element poistion:" + barIndex);
    var source= $(this).find("img").attr("src");
    img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
    img.attr('src', source);
    img.appendTo('.dreapta');
});

和小提琴 https://jsfiddle.net/eugensunic/rtcydtyh/15/