toggle()之后位置发生意外变化的原因是什么?

时间:2019-01-21 04:18:03

标签: javascript jquery

预期的行为:单击按钮并在按钮的右下方和右下方切换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>

下面是一个演示此行为的codepen:https://codepen.io/vorousjames/pen/omvxry?editors=1010

此行为的原因是什么?

4 个答案:

答案 0 :(得分:0)

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

您可以尝试:

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

获得所需的输出。

-帮助:)

答案 1 :(得分:0)

像这样将$( target ).toggle();移动到coordinates = $( element ).offset();上方

function toggleColorPicker ( element ) {

    var id, target, coordinates, newLeft, newTop;

    id = $( element ).attr( 'id' );
    target = "#colorBox" + id;
    $( target ).toggle();
    // position target relative to button pressed
    coordinates = $( element ).offset();
    newLeft = coordinates.left + 25;
    newTop = coordinates.top + 25;
    $( target ).offset( { top: newTop, left: newLeft } );


}

您可能想要在已知元素状态(隐藏或显示)之后执行偏移量计算,然后计算这些计算。我建议您了解为什么将来可能会发生这种情况的基本原理。 https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction

答案 2 :(得分:0)

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

        id = $(element).attr('id');
        target = "#colorBox" + id;

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

        $(target).toggle(); // Move this line from last to here, before setting the offset

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

    }

这是您的解决方案,将target-toggle移至offset的设置上方。

答案 3 :(得分:0)

我不确定为什么,但是如果将$(target).toggle()语句移到$(target).offset()语句上方,它将按预期工作。