当我增加窗口宽度时,边距将增加,当我减小窗口宽度时,边距将减少。

huangapple go评论70阅读模式
英文:

when I increase window width then margin will increase and when i decrease window width margin will reduce

问题

let getElement = document.getElementById("resize");
let width = window.innerWidth;
let arr = [];
arr.push(width);
let x = 1;
window.addEventListener("resize", () => {
  arr.reduce((current, old) => {
    if (current) {
      getElement.style.marginTop = `${(x += 1)}px`;
    } else {
      getElement.style.marginTop = `${(x -= 1)}px`;
    }
  }, width - 1);
});

if current value margin will increase and if old value margin will reduce

英文:
let getElement = document.getElementById("resize");
      let width = window.innerWidth;
      let arr = [];
      arr.push(width);
      let x = 1;
      window.addEventListener("resize", () => {
        arr.reduce((current, old) => {
          if (current) {
            getElement.style.marginTop = `${(x += 1)}px`;
          } else {
            getElement.style.marginTop = `${(x -= 1)}px`;
          }
        }, width - 1);
      });

if current value margin will increase and if old value margin will reduce

答案1

得分: 0

尝试以下代码

let getElement = document.getElementById("resize");
let arr = [window.innerWidth];
let x = 1;

window.addEventListener("resize", () => {
  let width = window.innerWidth;
  let diff = width - arr[arr.length - 1];

  if (diff > 0) {
    x += 1;
  } else if (diff < 0) {
    x -= 1;
  }

  getElement.style.marginTop = `${x}px`;

  arr.push(width);
});
英文:

Try the below code

let getElement = document.getElementById(&quot;resize&quot;);
let arr = [window.innerWidth];
let x = 1;

window.addEventListener(&quot;resize&quot;, () =&gt; {
  let width = window.innerWidth;
  let diff = width - arr[arr.length - 1];

  if (diff &gt; 0) {
    x += 1;
  } else if (diff &lt; 0) {
    x -= 1;
  }

  getElement.style.marginTop = `${x}px`;

  arr.push(width);
});

huangapple
  • 本文由 发表于 2023年2月18日 16:07:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定