首页 > 解决方案 > 合并函数和抽象(JavaScript)请帮助

问题描述

我是一个早期的初学者,并且拼命想让这段代码工作。请帮助或建议我。当鼠标打开或关闭时,我正在尝试使图标悬停(弹出和弹出)。:/

**HTML**

    <section id="ingredients"
    onmouseover="ingredientsHover('mouseover')" onmousedown="ingredientsNormal('mousedown')">
        <h2>ingredients  <i class="fa fa-coffee" aria-hidden="true"></i>
</h2>
    </section>
    <section id="preparation" onmouseover="preparationHover('mouseover')" onmousedown="preparationNormal('mousedown')">
      <a href="#" class="box">
        <h2>preparation  
        <i class="fa fa-list-alt" aria-hidden="true"></i>
</h2>

**JAVASCRIPT**

    function ingredientsHover(action) {
  if (action === 'mouseover') {
    document.getElementById('ingredients').firstElementChild.firstElementChild.style.fontSize = '300%';
  }
  else if (action === 'mousedown') {
    document.getElementById('ingredients').firstElementChild.firstElementChild.style.fontSize = '100%';
  }
}
}
function preparationHover(action) {
  if (action === 'mouseover') {
    document.getElementById('preparation').firstElementChild.firstElementChild.style.fontSize = '300%';
  }
  else if (action === 'mousedown') {
    document.getElementById('preparation').firstElementChild.firstElementChild.style.fontSize = '100%';
  }
}

标签: javascripthtmlfunction

解决方案


您可以在调用函数时传递一个附加参数,然后有条件地更改您的样式。

HTML:

<section id="ingredients" onmouseover="ingredientsHover(this,'mouseover')" onmousedown="ingredientsNormal(this,'mousedown')"></section>

JS:

function doSomething(element, action) {
  if(action === 'mouseover') {
     element.firstElementChild.firstElementChild.style.fontSize = '300%';
  } else if (action === 'mousedown') {
     element.firstElementChild.firstElementChild.style.fontSize = '100%';     
  }
}

推荐阅读