You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮与图片时元素未左移100px,jQuery动画失效问题

问题解决:jQuery点击动画左移未生效的修复方案

你的代码里有两个关键问题导致动画失效,下面是具体修复点和完整修正代码:

错误分析与修复

  • 元素定位缺失:p和img标签默认是static定位,这种定位模式下left属性不会产生位移效果。需要给目标元素添加position: relative(或absolute/fixed)。
  • 属性值格式错误:图片点击事件中的left: "100 px"存在空格,CSS数值与单位之间不能有空格,应改为"100px"。

修正后的完整代码

HTML部分

<body>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <style>
    /* 给需要动画的元素添加相对定位 */
    p, img {
      position: relative;
    }
  </style>
  <div class="mega-div">
    <p>text1</p>
    <img src="images indv4/1images.png">
    <p>text2</p>
    <img src="images indv4/2images.png">
    <p>text3</p>
    <img src="images indv4/3images.png">
    <p>text4</p>
    <img src="images indv4/4images.png">
    <p>text5</p>
  </div>

  <button class="left">Сместить параграфы</button>
</body>

JavaScript部分

$(document).ready(function() {
  $(".left").click(function() {
    let paragraphs = $("p");
    // 操作第三个p标签(索引从0开始)
    $(paragraphs[2]).animate({
      left: '100px'
    });
  })
  let images = $("img");
  $(images[1]).click(function() {
    // 修正属性值的空格问题,同时用$(this)指代当前点击元素更稳妥
    $(this).animate({
      left: "100px"
    });
  })
})

内容的提问来源于stack exchange,提问作者kR0Un

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:35:49