单击时将图像更改为div,再次单击时更改回img

时间:2015-04-20 10:43:50

标签: javascript jquery html css

正如标题所解释的那样,当我点击图片时,我试图将图像更改为div(带文本)。当我点击div时,我希望它改回图像。我尝试过某些东西,但没有一个可行。我的代码目前看起来像这样

images.click(function() {

            })

我需要一个功能,可以将图像更改为div,并在单击div时将其更改回来。

3 个答案:

答案 0 :(得分:1)

只需创建一个div作为图像的包装,并在单击图像后显示div。像这样:

<div id="wrapper">
   <img src="" id="yourImage"></img>
   <div id="divYouWantToShow">
   </div>
</div>

然后使用一些样式来隐藏div,这样图像才可见。

#divYouWantToShow{
  display:none;
}

之后你要做的就是JQuery。单击图像后,图像将隐藏,divYouWantToShow将显示,简单如下:

$('#yourImage').click(function(){
   $(this).hide(function(){
      $('#divYouWantToShow').show();
   });
});

如果点击div

则相同
$('#divYouWantToShow').click(function(){
   $(this).hide(function(){
      $('#yourImage').show();
   });
});

答案 1 :(得分:0)

尝试将图像和div放在包装器中并切换z-index:

$(document).on('click', '#wrp', function() {
  $(this).toggleClass('textTop');
});
#wrp {
  width: 256px;
  height: 256px;
  position: relative;
}
img,
#imgAlt {
  position: absolute;
  top: 0;
  left: 0;
}

img { z-index: 10 }

#imgAlt {
  width: 256px;
  height: 256px;
  background-color: green;
  color: #fff;
  z-index: 5;
}

#wrp.textTop #imgAlt { z-index: 15 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="wrp">
  <img src="http://www.pixeldecor.com/patterns/color-samples/brikbrak-sample.gif" />
  <div id="imgAlt">Text</div>
</div>

答案 2 :(得分:0)

<强> HTML

<div id="id">DIV</div>  

java脚本

$(document).on('click','#id',function(){

    var elementType = $(this).prop('tagName');
    if(elementType.toLowerCase() == 'div'){
        var image = '<img src="smiley.gif" alt="Smiley face" width="42" height="42" id="id">';
        $(this).remove();
        $('body').append(image);
    }
    else{
        var div = '<div id="id">DIV</div>';
        $(this).remove();
        $('body').append(div);
    }

});  

working demo