单击时更改元素位置

时间:2014-07-31 12:26:40

标签: javascript jquery css

我在jQuery Mobile中有这个代码,当我点击图像时它会变得更大。

我需要让图像向左和向上移动。

我试试这个:

<div class="ui-block-b">
        <p><img  id="zPIC" height="150" width="150" onclick="ZX();"/></p>
</div>


function ZX() {
    var img = $("#zPIC");
    if (img.width() < 200) {
       img.animate({ width: "200px", height: "200px", left: "20px", top: "20px" }, 1000);
    }
    else {
       img.animate({ width: img.attr("width"), height: img.attr("height") }, 1000);
    }
}

但是图片只会增长并且不会横向移动

1 个答案:

答案 0 :(得分:1)

您需要设置位置属性,例如相对的或绝对的。 E.g:

<div id="zPIC" style="position:relative; width:150px; min-height:150px; background:green"></div>

$(document).ready(function(){
  $("#zPIC").click(function(){
    if ($("#zPIC").width() < 200) {
      // store the original sizes
      $(this).data('width', $(this).css('width'));
      $(this).data('height', $(this).css('height'));
      $("#zPIC").animate({ width: "200px", height: "200px", left: "20px", top: "20px"      }, 1000);
    }
    else {
      $("#zPIC").animate({ width: $(this).data('width'), height: $(this).data('height'), }, 1000);
    }
  });
});