点击改变元素位置

Change element position on click

本文关键字:位置 元素 改变      更新时间:2023-09-26

我在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);
    }
}

但是图片只会变大,不会横向移动

你需要设置位置属性,例如相对或绝对。例如:

<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);
    }
  });
});