search

Home  >  Q&A  >  body text

javascript - 通过鼠标悬浮在a元素上,使图像透明度改变,为何在网页上没有变化,图像没有显示?

javascript//获得元素id
function getElement(id)
{
    return document.getElementById(id);
}

window.addEventListener("load",function()
{
       var helper1=function(index)
       {
         return getElement("btn-"+index);
       };
       //打算用闭包实现,创建闭包
       var helper2=function(index)
       {
           //获取图像元素
           var pictureElement=getElement("picture-"+index);
           //判断图像元素的透明度,如果为0,则用动画效果加到1
           //如果为1,则用动画效果减到0
           return function(){
               if(pictureElement.style.opacity==0)
                   pictureElement.animate(
                   {opacity:"+=1"},{duration:1000});
               else if(pictureElement.style.opacity==1)
                   pictureElement.animate(
                   {opacity:"-=1"},{duration:1000});
           };
       };
    for(var i=1;i<=8;i++)
    {
        var EventElement=helper1(i);
        //给每个a元素添加事件处理函数
        EventElement.addEventListener("mouseover",helper2(i));
    }
});

EventElement元素添加mouseover处理函数,判断另一个元素透明度,为什么不起作用?

天蓬老师天蓬老师2902 days ago372

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 15:10:38

    你这个代码其实很不规范。。。
    首先,闭包至少应该写成这样:

    return function(){
       if(pictureElement.style.opacity==0){
           pictureElement.animate({opacity:"+=1"},{duration:1000});
       } else if(pictureElement.style.opacity==1){
           pictureElement.animate({opacity:"-=1"},{duration:1000});
       }
    };
    

    另外,原生js没有animate方法,这个jQuery的方法。
    你可以先引用jQuery.js再使用$(el).animate();
    不妨试试看。

    reply
    0
  • Cancelreply