如何更改带有颜色阵列的mouseenter的背景

问题描述 投票:0回答:1

[很难弄清楚如何使用JavaScript将3个段落的背景色更改为mouseenter数组中的颜色。有小费吗?这是我的数组:

function changeColors() {
  var colors = ['pink', 'turquoise', 'green'];
javascript mouseenter
1个回答
0
投票

让我们说您的html就像这样:

<p class="my-paragraphs">Paragraph 1</p>
<p class="my-paragraphs">Paragraph 2</p>
<p class="my-paragraphs">Paragraph 3</p>

您的js将创建一个针对这些对象的数组,然后动态添加样式:

function changeColors() {
  var colors = ['pink', 'turquoise', 'green'];
  var myParagraphs = document.querySelectorAll('.my-paragraphs');

  myParagraphs.forEach( function(paragraph, index){
    paragraph.addEventListener('mouseover', function(){
      paragraph.style = `background-color: ${colors[index]}`
    })
    paragraph.addEventListener('mouseout', function(){
      paragraph.style = ``
    })
  })
}

changeColors()

Here is a codepen

有100万种方法,但我建议您不要在javascript中使用带有颜色名称的数组,而应创建包含background-color: anyColorYouLikeByPinkFloyd键值对的css类,然后使用javascript从中添加和删除这些类。您的段落。以编程方式更改JS中的style属性时应谨慎使用。

Here is a codepen that achieves the same effect with css classes。更详细,但更安全。以编程方式重写style="",就像我在上一个Codepen中所做的那样,将删除可能附加到您的元素的任何其他样式。

© www.soinside.com 2019 - 2024. All rights reserved.