【问题标题】:Div not resetting its default position after altered using javascript使用 javascript 更改后,Div 未重置其默认位置
【发布时间】:2018-04-12 15:28:50
【问题描述】:

我有一个高度和宽度为空的叠加层,一旦使用按钮单击它就会覆盖整个页面,这个叠加层从 top 0 left 0 一直向下过渡到右下角。关闭此覆盖层后,我使用 java 脚本编辑了 css 属性,以便它在右下角完成转换。

第一次打开和关闭此叠加层时,它工作正常,但是我第二次打开它时,它不是从左上角开始,而是从右下角开始并一直移动到左上角。我似乎无法解决这个问题。我尝试将左侧重置为 0 并将顶部重置为 0,但它不起作用。

document.querySelectorAll(".overlay_background")[0].addEventListener("click", parent);
   

function parent(event) {
  this.style.left = this.clientWidth + "px";
  this.style.top = this.clientHeight + "px";
  this.style.height = 0;
  this.style.width = 0;
}

function child(event) {
  event.stopPropagation();
}

function http_request_availability() {
  document.getElementById("overlay_background_id").style.left = "0";
  document.getElementById("overlay_background_id").style.top = "0";
  console.log(document.getElementById("overlay_background_id"));
  document.getElementById("overlay_background_id").style.height = "100vh";
  document.getElementById("overlay_background_id").style.width = "100vw";

  document.getElementById("overlay_background_id").style.backgroundColor = "rgba(0,0,0, 0.5)";
  document.body.style.overflow = "hidden";


}
.overlay_background {
  position: fixed;
  overflow: hidden;
  height: 0;
  width: 0;
  left: 0;
  top: 0;
  transition: 0.7s ease;
  z-index: 1;
}
<div class="overlay_background" id="overlay_background_id">
  Hi this is my overlay
</div>
<button class='btn_ws' onclick='http_request_availability();'>Book Work-Shop</button></div>

【问题讨论】:

  • Uncaught TypeError: Cannot read property 'addEventListener' of undefined。缺少.overlay_ws_container
  • 我删除了那段代码。再试一次:)
  • 这是因为在父级内部关闭时,您从未将 left + top 属性设置回 0,您不能这样做,因为它会干扰当前的自顶向下动画。
  • 感谢您花时间解释,我有点想过,但我不知道如何解决这个问题

标签: javascript css


【解决方案1】:

问题是您的叠加层永远不会重置为其原始位置的顶部 0 和左侧 0。

尝试将其添加到 parent() 函数的末尾:

var self = this;
setTimeout(function() {
    self.style.left = 0;
    self.style.top = 0;
 }, 700);

这将在 700 毫秒后(过渡的持续时间)将左侧和顶部位置重置为 0。

【讨论】:

  • 感谢您的回答,我正在考虑这样的事情,但不知道我是否正确。每次鼠标在网页内移动时,我也一直在考虑不断添加左 0 和前 0,但我认为这是一种不好的做法:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-19
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多