首页 > 解决方案 > toggle() 后位置发生意外变化的原因是什么?

问题描述

预期行为:单击按钮并将 div#colorBox1 的显示切换到按钮的略下方和右侧。

经验丰富的行为:第一次单击按钮时,div 的显示按预期工作。但是,第二次切换 div 外观时,在不刷新页面的情况下,div 比第一次切换外观更靠右,更靠下。

从那时起,每次切换外观时,div 都会保持在第二个、更低、更靠右的位置。

旁注:刷新页面后,第一次切换的外观,div 位置将是正确的。

JS:

function toggleColorPicker(element) {
  let id,
    target,
    coordinates,
    newLeft,
    newTop;

  id = $(element).attr('id');
  target = `#colorBox${id}`;

  coordinates = $(element).offset();
  newLeft = coordinates.left + 25;
  newTop = coordinates.top + 25;

  $(target).offset({ top: newTop, left: newLeft });

  $(target).toggle();
}

HTML:

<div>
  <button onclick="toggleColorPicker(this);" type="button" id="1"></button>
  <div
    id="colorBox1"
    style="height:300px; width: 300px; background-color: black; position: absolute; display:none;"
  >
    <label for="promptTextColor">
      <input
        style="display:none;"
        class="form-control"
        name="promptTextColor"
        id="promptTextColor"
        type="text"
      />

      <canvas id="colorCanvas1" class="color-canvas" width="250" height="250"></canvas>
    </label>
  </div>
</div>

这是一个演示此行为的代码笔:https ://codepen.io/vorousjames/pen/omvxry?editors=1010

这种行为的原因是什么?

标签: javascriptjquery

解决方案


$( target ).offset( { top: newTop, left: newLeft } )没有正确重置。

你可以试试 :

$( target ).css( { top: newTop, left: newLeft } ) 

为所需的输出。

-帮助 :)


推荐阅读