【问题标题】:change image into div when clicked, and change back to img when clicked again单击时将图像更改为div,再次单击时更改回img
【发布时间】:2015-06-27 01:09:00
【问题描述】:

正如标题所解释的,当我单击图像时,我试图将图像更改为 div(带文本)。当我单击 div 时,我希望它变回图像。我已经尝试了某些东西,但没有一个有效。我现在的代码是这样的

images.click(function() {

            })

我需要一个将图像更改为 div 并在单击 div 时将其更改回的函数。

【问题讨论】:

  • 绝对有必要“更改”标签吗?您可以使用imgdiv 并分别显示和隐藏它们吗?
  • SO 不是代码编写服务。至少向我们展示您的 HTML 以及到目前为止您尝试过的 JQuery。

标签: javascript jquery html css


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    只需创建一个 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();
       });
    });
    

    【讨论】:

      【解决方案3】:

      尝试将图像和 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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        相关资源
        最近更新 更多