如何使用mouseover和mouseout事件来更改生成的divs/grid-items的背景颜色。

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

How to use the mouseover and mouseout events to change background color of all of the generated divs/grid-items

问题

我正在完成"etch-a-sketch"挑战,作为TOP课程的一部分。我已成功使用JS DOM操控和CSS网格创建了一个16x16的网格。问题的第二部分是使每个单独的网格项/单元在悬停时更改背景颜色。我选择使用JS的mouseover事件监听器,但也在搜索信息时看到了CSS的:hover选择器作为一个可行的选项。

我创建了两个函数"overing"和"outing",用于在悬停时更改网格项的背景颜色,使用"mouseover"事件监听器。这些函数只在第一个生成的单元/网格项上有效。请问如何使"overing"和"outing"函数在所有网格项上工作?仅第1个网格项有效

英文:

I am completing the "etch-a-sketch" challenge as part of TOP curriculum. I have successfully created a 16 x 16 grid utilizing JS DOM manipulation and CSS grid. The second part of my problem is to make each individual grid-item/cell change background color on hover. I chose to use JS with the mouseover Eventlistener, but also saw the CSS: hover Selector as a viable option when googling for information.

I have created 2 functions overing and outing to change the background color of the grid-item on hover using the "mouseover" event listener. The functions only work on the first generated cell/grid-item. May someone please explain how I can get my overing and outing functions to work on all grid-items.only 1st grid-item working

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. //Function and call to generate 16x16 grid of divs.
  2. document.getElementById(&quot;container&quot;);
  3. function makeGrid(rows, cols) {
  4. container.style.setProperty(&#39;--grid-rows&#39;, rows)
  5. container.style.setProperty(&#39;--grid-cols&#39;, cols)
  6. for (c = 0; c &lt; (rows * cols); c++) {
  7. let cell = document.createElement(&quot;div&quot;);
  8. cell.innerText = (c + 1);
  9. container.appendChild(cell).className = &quot;grid-item&quot;;
  10. };
  11. };
  12. makeGrid(16, 16);
  13. //Function to change background color of individual &quot;grid-item&quot; on hover.
  14. document.querySelector(&#39;.grid-item&#39;).addEventListener(&#39;mouseover&#39;, overing);
  15. document.querySelector(&#39;.grid-item&#39;).addEventListener(&#39;mouseout&#39;, outing);
  16. function overing(ev) {
  17. ev.currentTarget.style.backgroundColor = &#39;red&#39;;
  18. console.log(&#39;mouseenter div&#39;);
  19. }
  20. function outing(ev) {
  21. ev.currentTarget.style.backgroundColor = &#39;white&#39;;
  22. console.log(&#39;mouseleave div&#39;);
  23. }

<!-- language: lang-css -->

  1. :root {
  2. --grid-cols: 1;
  3. --grid-rows: 1;
  4. }
  5. #container {
  6. display: grid;
  7. grid-gap: 1em;
  8. grid-template-columns: repeat(var(--grid-cols), 1fr);
  9. grid-template-rows: repeat(var(--grid-rows), 1fr);
  10. }
  11. .grid-item {
  12. padding: 1em;
  13. border: 1px solid black;
  14. text-align: center;
  15. }

<!-- language: lang-html -->

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html lang=&quot;en&quot;&gt;
  3. &lt;head&gt;
  4. &lt;meta charset=&quot;UTF-8&quot;&gt;
  5. &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
  6. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  7. &lt;title&gt;Sketch-Book&lt;/title&gt;
  8. &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;etchStyles.css&quot; /&gt;
  9. &lt;/head&gt;
  10. &lt;body&gt;
  11. &lt;div id=&quot;container&quot;&gt;
  12. &lt;/div&gt;
  13. &lt;/body&gt;
  14. &lt;script type=&quot;text/javascript&quot; src=&quot;etchScript.js&quot;&gt;&lt;/script&gt;
  15. &lt;/html&gt;

<!-- end snippet -->

答案1

得分: 4

@Titus 是对的。但由于您正在使用JavaScript创建每个DOM节点,您可以利用这一点在创建时附加事件侦听器。例如:

  1. const overing = (ev) => {
  2. ev.currentTarget.style.backgroundColor = 'red';
  3. };
  4. const outing = (ev) => {
  5. ev.currentTarget.style.backgroundColor = 'white';
  6. }
  7. const makeGrid = (rows, cols) => {
  8. container.style.setProperty('--grid-rows', rows)
  9. container.style.setProperty('--grid-cols', cols)
  10. for (c = 0; c < (rows * cols); c++) {
  11. let cell = document.createElement("div");
  12. cell.innerText = (c + 1);
  13. cell.classList.add('grid-item');
  14. // 在此处附加事件侦听器,因为您有对DOM节点的引用
  15. cell.addEventListener("mouseover", overing);
  16. cell.addEventListener("mouseout", outing);
  17. container.appendChild(cell);
  18. };
  19. };
  20. makeGrid(16, 16);

此代码段演示了如何在创建每个DOM节点时附加事件侦听器,以便在鼠标悬停和移出时更改背景颜色。

英文:

@Titus is right. But since you are using javascript to create each DOM node, you can exploit this fact to attach event listeners at creation time. Ex:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const overing = (ev) =&gt; {
  2. ev.currentTarget.style.backgroundColor = &#39;red&#39;;
  3. //console.log(&#39;mouseenter div&#39;);
  4. };
  5. const outing = (ev) =&gt; {
  6. ev.currentTarget.style.backgroundColor = &#39;white&#39;;
  7. //console.log(&#39;mouseleave div&#39;);
  8. }
  9. const makeGrid = (rows, cols) =&gt; {
  10. container.style.setProperty(&#39;--grid-rows&#39;, rows)
  11. container.style.setProperty(&#39;--grid-cols&#39;, cols)
  12. for (c = 0; c &lt; (rows * cols); c++) {
  13. let cell = document.createElement(&quot;div&quot;);
  14. cell.innerText = (c + 1);
  15. cell.classList.add(&#39;grid-item&#39;);
  16. // attach listeners here since you have a reference to the DOM node
  17. cell.addEventListener(&quot;mouseover&quot;, overing);
  18. cell.addEventListener(&quot;mouseout&quot;, outing);
  19. container.appendChild(cell);
  20. };
  21. };
  22. makeGrid(16, 16);

<!-- language: lang-css -->

  1. section {
  2. --grid-cols: 1;
  3. --grid-rows: 1;
  4. }
  5. #container {
  6. display: grid;
  7. grid-gap: 1em;
  8. grid-template-columns: repeat(var(--grid-cols), 1fr);
  9. grid-template-rows: repeat(var(--grid-rows), 1fr);
  10. }
  11. .grid-item {
  12. padding: 1em;
  13. border: 1px solid black;
  14. text-align: center;
  15. }
  16. .grid-item:hover {
  17. cursor: pointer;
  18. }

<!-- language: lang-html -->

  1. &lt;section&gt;
  2. &lt;div id=&quot;container&quot;&gt;
  3. &lt;/div&gt;
  4. &lt;/section&gt;

<!-- end snippet -->

答案2

得分: 2

你可以使用CSS的:hover伪类,这里有一个3x3网格的示例:

  1. .grid {
  2. display: grid;
  3. grid-template: repeat(3, 30vh) / repeat(3, 30vw);
  4. background-color: white;
  5. height: 94vh;
  6. width: 94vw;
  7. grid-row-gap: 1vh;
  8. grid-column-gap: 1vw;
  9. }
  10. .grid_element {
  11. display: flex;
  12. height: 100%;
  13. width: 100%;
  14. background-color: gray;
  15. }
  16. .grid_element:hover {
  17. background-color: red;
  18. }
  1. <div class="grid">
  2. <div class="grid_element"></div>
  3. <div class="grid_element"></div>
  4. <div class="grid_element"></div>
  5. <div class="grid_element"></div>
  6. <div class="grid_element"></div>
  7. <div class="grid_element"></div>
  8. <div class="grid_element"></div>
  9. <div class="grid_element"></div>
  10. <div class="grid_element"></div>
  11. </div>
英文:

You could use css :hover, here is an example with a 3x3 grid:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

  1. .grid {
  2. display: grid;
  3. grid-template: repeat(3, 30vh) / repeat(3, 30vw);
  4. background-color: white;
  5. height: 94vh;
  6. width: 94vw;
  7. grid-row-gap:1vh;
  8. grid-column-gap:1vw;
  9. }
  10. .grid_element {
  11. display: flex;
  12. height: 100%;
  13. width: 100%;
  14. background-color: gray;
  15. }
  16. .grid_element:hover {
  17. background-color: red;
  18. }

<!-- language: lang-html -->

  1. &lt;div class=&quot;grid&quot;&gt;
  2. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  3. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  4. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  5. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  6. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  7. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  8. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  9. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  10. &lt;div class=&quot;grid_element&quot;&gt;&lt;/div&gt;
  11. &lt;/div&gt;

<!-- end snippet -->

答案3

得分: 1

所有现代浏览器都支持模板引用:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template,因此我们可以使用它来代替手动创建元素,这样我们的代码可以更小 - 尤其是如果您要为每个“单元格”添加更多内容,如一组跨度、div 等。

您可以确定要添加事件处理程序,但您可以在创建它们的相同循环中添加它们。

注意:可能需要创建一个新的 DIV,用于在命中 DOM 之前将所有新项目附加到它,但我将把这个练习留给您,因为它超出了问题的范围。

  1. function makeGrid(rows, cols) {
  2. const container = document.getElementById("container");
  3. const template = document.getElementById("grid-cell-template");
  4. for (let c = 0; c < (rows * cols); c++) {
  5. const cloneCell = template.content.cloneNode(true);
  6. const newItem = cloneCell.querySelector(".grid-item");
  7. newItem.textContent = (c + 1);
  8. newItem.addEventListener('mouseenter', mouseEnterEventHandler);
  9. newItem.addEventListener('mouseleave', mouseLeaveEventHandler);
  10. newItem.addEventListener('mouseover', mouseOverEventHandler);
  11. container.appendChild(newItem);
  12. }
  13. }
  14. makeGrid(16, 16);
  15. function mouseEnterEventHandler(event) {
  16. event.currentTarget.style.backgroundColor = '#FF000022';
  17. }
  18. function mouseLeaveEventHandler(event) {
  19. event.currentTarget.style.backgroundColor = '#FFFFFF';
  20. event.target.style.borderColor = "#000000";
  21. }
  22. function mouseOverEventHandler(event) {
  23. event.target.style.borderColor = "#00FF00";
  24. }
  1. body {
  2. font-size: 16px;
  3. margin: 0;
  4. padding: 0;
  5. box-sizing: border-box;
  6. }
  7. :root {
  8. --grid-cols: 16;
  9. --grid-rows: 16;
  10. }
  11. #container {
  12. display: grid;
  13. grid-gap: 0.5em;
  14. grid-template-columns: repeat(var(--grid-cols), 1fr);
  15. grid-template-rows: repeat(var(--grid-rows), 1fr);
  16. }
  17. .grid-item {
  18. padding: 1em;
  19. border: 1px solid #000000;
  20. text-align: center;
  21. }
  1. <body>
  2. <div id="container">
  3. </div>
  4. <template id="grid-cell-template">
  5. <div class="grid-item"></div>
  6. </template>
  7. </body>

以上为您提供的代码部分的翻译。

英文:

All modern browsers support template ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template so lets' use that instead of manually creating an element so out code can be smaller - especially if you add more content to each "cell" such as a set of spans, divs etc.

You can determine what you want for event handlers but you can add those right in the same loop when creating them.

NOTE: Probably want to create a new DIV just to append all the NEW items to before hitting the DOM and appending them all at once but I will leave that exercise to you as outside the question scope.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. function makeGrid(rows, cols) {
  2. const container = document.getElementById(&quot;container&quot;);
  3. const template = document.getElementById(&quot;grid-cell-template&quot;);
  4. for (let c = 0; c &lt; (rows * cols); c++) {
  5. const cloneCell = template.content.cloneNode(true);
  6. const newItem = cloneCell.querySelector(&quot;.grid-item&quot;);
  7. newItem.textContent = (c + 1);
  8. newItem.addEventListener(&#39;mouseenter&#39;, mouseEnterEventHandler);
  9. newItem.addEventListener(&#39;mouseleave&#39;, mouseLeaveEventHandler);
  10. newItem.addEventListener(&#39;mouseover&#39;, mouseOverEventHandler);
  11. container.appendChild(newItem);
  12. }
  13. }
  14. makeGrid(16, 16);
  15. function mouseEnterEventHandler(event) {
  16. event.currentTarget.style.backgroundColor = &#39;#FF000022&#39;;
  17. }
  18. function mouseLeaveEventHandler(event) {
  19. event.currentTarget.style.backgroundColor = &#39;#FFFFFF&#39;;
  20. event.target.style.borderColor = &quot;#000000&quot;;
  21. }
  22. function mouseOverEventHandler(event) {
  23. event.target.style.borderColor = &quot;#00FF00&quot;;
  24. }

<!-- language: lang-css -->

  1. body {
  2. font-size: 16px;
  3. margin: 0;
  4. padding: 0;
  5. box-sizing: border-box;
  6. }
  7. :root {
  8. --grid-cols: 16;
  9. --grid-rows: 16;
  10. }
  11. #container {
  12. display: grid;
  13. grid-gap: 0.5em;
  14. grid-template-columns: repeat(var(--grid-cols), 1fr);
  15. grid-template-rows: repeat(var(--grid-rows), 1fr);
  16. }
  17. .grid-item {
  18. padding: 1em;
  19. border: 1px solid #000000;
  20. text-align: center;
  21. }

<!-- language: lang-html -->

  1. &lt;body&gt;
  2. &lt;div id=&quot;container&quot;&gt;
  3. &lt;/div&gt;
  4. &lt;template id=&quot;grid-cell-template&quot;&gt;
  5. &lt;div class=&quot;grid-item&quot;&gt;&lt;/div&gt;
  6. &lt;/template&gt;
  7. &lt;/body&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月10日 23:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978353.html
匿名

发表评论

匿名网友

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

确定