javascript - 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
这种行为的原因是什么?
解决方案
$( target ).offset( { top: newTop, left: newLeft } )
没有正确重置。
你可以试试 :
$( target ).css( { top: newTop, left: newLeft } )
为所需的输出。
-帮助 :)
推荐阅读
- java - 代码重构:对 Resttemplate 的 CloseableHttpResponse
- woocommerce - Woocommerce 获取产品类别路径
- java - 如何从两种不同类型的列表创建对象列表
- javascript - Uncaught (in promise) TypeError: this.getChildrem is not a function
- arduino - 最大化 Arduino Nano 33 BLE Sense 的 Serial.write() 数据传输速度
- python - 加载 tensorflow 模型时出错 - TypeError: __init__() got an unexpected keyword argument 'axis'
- javascript - 将颜色应用于单击的表格行
- html - 如何创建适合所有屏幕尺寸的 Web 应用程序?
- html - 内容安全策略元标记“不安全内联”不起作用
- sql-server - SQL 触发器的想法