【问题标题】:How to change backgrounds on mouseenter with array of colors如何使用颜色数组更改 mouseenter 的背景
【发布时间】:2020-01-22 00:12:13
【问题描述】:

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

function changeColors() {
  var colors = ['pink', 'turquoise', 'green'];

【问题讨论】:

    标签: javascript mouseenter


    【解决方案1】:

    假设你的 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

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

    Here is a codepen that achieves the same effect with css classes。更冗长,但更安全。像我在之前的 codepen 中那样以编程方式重写 style="" 将删除可能附加到您的元素的任何其他样式。

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 2018-12-26
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      相关资源
      最近更新 更多