我想触发不透明过渡。如果光标将元素悬停,则光标应淡出,更改其背景图像,然后再次淡入。我想通过添加和删除css类来实现。它不起作用,怎么了?

js fiddle

的HTML

<div class="wrapper">
   <div class="cursor">
   </div>
   <div id="grey">
   </div>
</div>


的CSS

.wrapper {
width: 100%;
height: 100%;
background-color: lightgrey;
padding: 60px;
cursor: none;
}

#grey {
width: 100px;
height: 100px;
background: grey;

}

.cursor {
position: fixed;
width: 20px;
height: 20px;
pointer-events: none;
opacity: 0;
-webkit-transition: opacity .3s; /* Safari */
transition: opacity .3s;
}

.red {
background: red;
opacity: 1;
}

.green {
background: green;
opacity: 1;
}


JS

  $('.wrapper').on('mousemove', function(e){
        $('.cursor').css('left', e.clientX-10).css('top', e.clientY -10);
       if ($.contains($('.wrapper')[0], e.target)){

        $('.cursor').removeClass('green').addClass('red');
    }else{
        $('.cursor').removeClass('red').addClass('green');
    }
});

最佳答案

DEMO HERE

好,你去。您需要在这里跟踪已经部分完成的两件事,还要等待fadeOut完成并添加用于添加和删除相应class的回调


  
  光标是否已输入元素
  光标是否有左元素
  


以下是您实际可以执行的操作。

var entered=false;//global variables to show the position of cursor
var left=false;
$('.wrapper').on('mousemove', function(e){
    $('.cursor').css('left', e.clientX-10).css('top', e.clientY -10);
    if ($.contains($('.wrapper')[0], e.target)){
        if(!entered)
        {
            //just to do it once and not on every mousemove you need to check here whether
            //it has already entered and moving inside the element
            entered=true;
            left=false;//to check the vice versa operation
            $('.cursor').fadeOut('fast',function(){
                //callback function after fadeOut completes
                $(this).removeClass('green').addClass('red');
            }).fadeIn('fast');
        }
    }else{
        if(!left)
        {
            left=true;
            entered=false;
            //same goes here too
            $('.cursor').fadeOut('fast',function(){
                $(this).removeClass('red').addClass('green');
            }).fadeIn('fast');
        }
    }
});

关于javascript - 在鼠标移入和移出时触发不透明度转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33866055/

10-12 04:46