页面没有用小屏幕显示正确的布局

发布于 2025-02-05 21:05:40 字数 6416 浏览 1 评论 0原文

在751px或更高版本中显示时,布局开始良好,但在750px或更少的情况下启动时无法正常工作。我认为下面在我的JavaScript中可以使用此代码,但事实并非如此。

// does not seem to work when page is loaded
window.addEventListener("load", () => {
    window.innerWidth <= 750 ? columnLayout() : rowLayout();
});

const colorPickerEl = document.getElementById("color-picker");
const colorSchemeContainerEl = document.getElementById(
  "color-scheme-container"
);
const colorModeEl = document.getElementById("color-mode");
const headerEl = document.getElementById("header");

// display default scheme
displayColorScheme(colorPickerEl.value.slice(1), "monochrome");

/*-------------
Event Listeners
---------------*/

// listen for when a new scheme is requested
document.getElementById("get-scheme-btn").addEventListener("click", () => {
  displayColorScheme(colorPickerEl.value.slice(1));
});

// listen for when a randomized scheme is requested
document
  .getElementById("randomize-scheme-btn")
  .addEventListener("click", () => {
    displayColorScheme(generateRandomColor());
  });

// does not seem to work when page is loaded
window.addEventListener("load", () => {
  window.innerWidth <= 750 ? columnLayout() : rowLayout();
});

window
  .matchMedia("screen and (max-width: 750px)")
  .addEventListener("change", (event) => {
    if (event.matches) {
      columnLayout();
    }
  });

window
  .matchMedia("screen and (min-width: 751px)")
  .addEventListener("change", (event) => {
    if (event.matches) {
      rowLayout();
    }
  });

function columnLayout() {
  document.getElementById(
    "spacer"
  ).style.height = `${headerEl.offsetHeight}px`;
  const colorBars = document.getElementsByClassName("color-bar");
  let barHeight =
    (colorSchemeContainerEl.offsetHeight - headerEl.offsetHeight) / 5;
  for (const bar of colorBars) {
    console.log(bar);
    bar.style.height = `${barHeight}px`;
  }
}

function rowLayout() {
  console.log("row");
  const colorBars = document.getElementsByClassName("color-bar");
  for (const bar of colorBars) {
    bar.style.height = `${colorSchemeContainerEl.offsetHeight}px`;
  }
}

// display color scheme based on user-picked color (or randomized color) and mode
function displayColorScheme(seed) {
  const mode = colorModeEl.value;
  // fetch the scheme using an api
  fetch(`https://www.thecolorapi.com/scheme?hex=${seed}&mode=${mode}`)
    // convert the data from json
    .then((response) => response.json())
    // manipulate the data
    .then((data) => {
      let html = "";
      for (const color of data.colors) {
        const totalRGBValue = color.rgb.r + color.rgb.g + color.rgb.b;
        // 127 + 127 + 127 (the middle threshold)
        const midRGBValue = 381;
        const textColor =
          totalRGBValue <= midRGBValue ? "white" : "black";
        html += `
                    <div class="color-bar" style="background-color:${color.hex.value};"><p class= "text-color-bar" style="color:${textColor};">${color.hex.clean}<p></div>
                `;
      }
      let spacer = `
                <div id="spacer"></div>
            `;
      colorSchemeContainerEl.innerHTML = spacer + html;
    });
}

// generate a random color in hex format
function generateRandomColor() {
  const characters = "0123456789ABCDEF";
  const maxLength = 6;
  let color = "";
  for (let i = 0; i < maxLength; i++) {
    color += characters.charAt(
      Math.floor(Math.random() * characters.length)
    );
  }
  colorPickerEl.value = "#" + color;
  return color;
}
html,
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

form {
  display: flex;
  justify-content: space-evenly;
}

header {
  padding: 30px 0;
  background-color: transparent;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
  background-color: white;
  box-shadow: 0 6px 10px -4px #222;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

input[type="button"],
select {
  padding: 0 10px;
  font-size: 1.05rem;
}

#color-picker {
  height: 3.5em;
  width: 10%;
}

p.colorName {
  border: 1.5px solid rgb(70, 70, 70);
  border-radius: 5px;
  padding: 10px;
}

select {
  width: 30%;
  text-align: center;
}

.color-bar {
  display: flex;
  justify-content: center;
  align-items: center;
}

.text-color-bar {
  margin: 0;
  font-size: 1.1rem;
  letter-spacing: 0.1rem;
}

#color-scheme-container {
  height: 100vh;
}

@media screen and (max-width: 750px) {
  #color-scheme-container {
    flex-direction: column;
  }
  #spacer {
    width: 100%;
    /* height: calc(60px + 3.5em - 9px); */
  }
  .color-bar {
    width: 100%;
    /* height: 17.94%; */
  }
}

@media screen and (min-width: 751px) {
  #color-scheme-container {
    width: 100%;
    display: flex;
    position: relative;
  }
  .color-bar {
    width: 20%;
  }
}
<header id="header">
  <form id="color-form">
    <input type="color" id="color-picker" value="#008080" />
    <select name="mode" id="color-mode">
      <option value="monochrome">Monochrome</option>
      <option value="monochrome-dark">Monochrome Dark</option>
      <option value="monochrome-light">Monochrome Light</option>
      <option value="analogic">Analogic</option>
      <option value="complement">Complement</option>
      <option value="analogic-complement">
        Analogic Complement
      </option>
      <option value="triad">Triad</option>
      <option value="quad">Quad</option>
    </select>
    <input id="get-scheme-btn" type="button" value="Get Color Scheme" />
    <input id="randomize-scheme-btn" type="button" value="Radomize Scheme" />
  </form>
</header>
<main>
  <div id="color-scheme-container"></div>
</main>

请注意,我无法获得标头元素的高度,并在CSS中将其分配给我的间隔div。我必须经过JS并将其设置在那里。任何帮助将不胜感激。

我在做什么错?为什么AddEventListener“加载”代码不起作用?

这是一个可以尝试此问题的链接: https://massuhcolorschemegenerator.netlify.netlify.app/

The layout starts-off fine when displayed in 751px or greater but does not work fine when it starts-off in 750px or less. I thought this code below in my javascript would work but it doesn't.

// does not seem to work when page is loaded
window.addEventListener("load", () => {
    window.innerWidth <= 750 ? columnLayout() : rowLayout();
});

const colorPickerEl = document.getElementById("color-picker");
const colorSchemeContainerEl = document.getElementById(
  "color-scheme-container"
);
const colorModeEl = document.getElementById("color-mode");
const headerEl = document.getElementById("header");

// display default scheme
displayColorScheme(colorPickerEl.value.slice(1), "monochrome");

/*-------------
Event Listeners
---------------*/

// listen for when a new scheme is requested
document.getElementById("get-scheme-btn").addEventListener("click", () => {
  displayColorScheme(colorPickerEl.value.slice(1));
});

// listen for when a randomized scheme is requested
document
  .getElementById("randomize-scheme-btn")
  .addEventListener("click", () => {
    displayColorScheme(generateRandomColor());
  });

// does not seem to work when page is loaded
window.addEventListener("load", () => {
  window.innerWidth <= 750 ? columnLayout() : rowLayout();
});

window
  .matchMedia("screen and (max-width: 750px)")
  .addEventListener("change", (event) => {
    if (event.matches) {
      columnLayout();
    }
  });

window
  .matchMedia("screen and (min-width: 751px)")
  .addEventListener("change", (event) => {
    if (event.matches) {
      rowLayout();
    }
  });

function columnLayout() {
  document.getElementById(
    "spacer"
  ).style.height = `${headerEl.offsetHeight}px`;
  const colorBars = document.getElementsByClassName("color-bar");
  let barHeight =
    (colorSchemeContainerEl.offsetHeight - headerEl.offsetHeight) / 5;
  for (const bar of colorBars) {
    console.log(bar);
    bar.style.height = `${barHeight}px`;
  }
}

function rowLayout() {
  console.log("row");
  const colorBars = document.getElementsByClassName("color-bar");
  for (const bar of colorBars) {
    bar.style.height = `${colorSchemeContainerEl.offsetHeight}px`;
  }
}

// display color scheme based on user-picked color (or randomized color) and mode
function displayColorScheme(seed) {
  const mode = colorModeEl.value;
  // fetch the scheme using an api
  fetch(`https://www.thecolorapi.com/scheme?hex=${seed}&mode=${mode}`)
    // convert the data from json
    .then((response) => response.json())
    // manipulate the data
    .then((data) => {
      let html = "";
      for (const color of data.colors) {
        const totalRGBValue = color.rgb.r + color.rgb.g + color.rgb.b;
        // 127 + 127 + 127 (the middle threshold)
        const midRGBValue = 381;
        const textColor =
          totalRGBValue <= midRGBValue ? "white" : "black";
        html += `
                    <div class="color-bar" style="background-color:${color.hex.value};"><p class= "text-color-bar" style="color:${textColor};">${color.hex.clean}<p></div>
                `;
      }
      let spacer = `
                <div id="spacer"></div>
            `;
      colorSchemeContainerEl.innerHTML = spacer + html;
    });
}

// generate a random color in hex format
function generateRandomColor() {
  const characters = "0123456789ABCDEF";
  const maxLength = 6;
  let color = "";
  for (let i = 0; i < maxLength; i++) {
    color += characters.charAt(
      Math.floor(Math.random() * characters.length)
    );
  }
  colorPickerEl.value = "#" + color;
  return color;
}
html,
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

form {
  display: flex;
  justify-content: space-evenly;
}

header {
  padding: 30px 0;
  background-color: transparent;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 99;
  background-color: white;
  box-shadow: 0 6px 10px -4px #222;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

input[type="button"],
select {
  padding: 0 10px;
  font-size: 1.05rem;
}

#color-picker {
  height: 3.5em;
  width: 10%;
}

p.colorName {
  border: 1.5px solid rgb(70, 70, 70);
  border-radius: 5px;
  padding: 10px;
}

select {
  width: 30%;
  text-align: center;
}

.color-bar {
  display: flex;
  justify-content: center;
  align-items: center;
}

.text-color-bar {
  margin: 0;
  font-size: 1.1rem;
  letter-spacing: 0.1rem;
}

#color-scheme-container {
  height: 100vh;
}

@media screen and (max-width: 750px) {
  #color-scheme-container {
    flex-direction: column;
  }
  #spacer {
    width: 100%;
    /* height: calc(60px + 3.5em - 9px); */
  }
  .color-bar {
    width: 100%;
    /* height: 17.94%; */
  }
}

@media screen and (min-width: 751px) {
  #color-scheme-container {
    width: 100%;
    display: flex;
    position: relative;
  }
  .color-bar {
    width: 20%;
  }
}
<header id="header">
  <form id="color-form">
    <input type="color" id="color-picker" value="#008080" />
    <select name="mode" id="color-mode">
      <option value="monochrome">Monochrome</option>
      <option value="monochrome-dark">Monochrome Dark</option>
      <option value="monochrome-light">Monochrome Light</option>
      <option value="analogic">Analogic</option>
      <option value="complement">Complement</option>
      <option value="analogic-complement">
        Analogic Complement
      </option>
      <option value="triad">Triad</option>
      <option value="quad">Quad</option>
    </select>
    <input id="get-scheme-btn" type="button" value="Get Color Scheme" />
    <input id="randomize-scheme-btn" type="button" value="Radomize Scheme" />
  </form>
</header>
<main>
  <div id="color-scheme-container"></div>
</main>

Please note that I can't get the height of my header element and assign it to my spacer div, in CSS. I have to go through my JS and set the height there. Any help is greatly appreciated.

What am I doing wrong? Why isn't the addeventlistener "load" code working?

Here's a link where you can try out the issue:
https://massuhcolorschemegenerator.netlify.app/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我最亲爱的 2025-02-12 21:05:40

我找到了答案!我要做的就是将代码放置:

window.innerWidth <= 750 ? columnLayout() : rowLayout();

在我的 displayColorscheme 函数的 end 上。

它运作完美。

I found the answer! All I needed to do was put my code:

window.innerWidth <= 750 ? columnLayout() : rowLayout();

at the end of my displayColorScheme function.

It worked perfectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文