2015-05-09 67 views
1

我想在鼠標懸停在div上時發生微妙的移動。鼠標移動背景運動

但是,微妙的部分並沒有完全解決。

只要將鼠標懸停在上面,背景圖像就會跳轉。

$(document).ready(function() { 
    var movementStrength = 50; 
    var height = movementStrength/$(window).height(); 
    var width = movementStrength/$(window).width(); 
    $("#bg").mousemove(function(e){ 
       var pageX = e.pageX - ($(window).width()/2); 
       var pageY = e.pageY - ($(window).height()/2); 
       var newvalueX = width * pageX * -1 - 25; 
       var newvalueY = height * pageY * -1 - 50; 
       $('#bg').css("background-position", newvalueX+"px  "+newvalueY+"px"); 
    }); 
}); 

https://jsfiddle.net/cjnLtcr0/2/

+0

你想要延遲還是稍微移動? – renakre

+0

我在找輕微的動作 – John

+0

你可以試試'newvalueX/5 +「px」+ newvalueY/5 +「px」' – renakre

回答

1

你可以添加一個類與過渡,使用超時等待過渡結束,然後取出類:

$(document).ready(function() { 
 
    var movementStrength = 50; 
 
    var height = movementStrength/$(window).height(); 
 
    var width = movementStrength/$(window).width(); 
 
    $("#bg").on({ 
 
    mouseenter: function(e) { // on mouse enter 
 
     var pageX = e.pageX - ($(window).width()/2); 
 
     var pageY = e.pageY - ($(window).height()/2); 
 
     var newvalueX = width * pageX * -1 - 25; 
 
     var newvalueY = height * pageY * -1 - 50; 
 

 
     $('#bg').addClass('transition'); // add a transition 
 

 
     $('#bg').css({ // move background with transition 
 
     "background-position": newvalueX + "px  " + newvalueY + "px" 
 
     }); 
 

 
     setTimeout(function() { // wait .3s 
 
     $('#bg').removeClass('transition'); // remove the transition 
 
     }, 300); 
 
    }, 
 

 
    mousemove: function(e) { // on mouse move 
 
     var pageX = e.pageX - ($(window).width()/2); 
 
     var pageY = e.pageY - ($(window).height()/2); 
 
     var newvalueX = width * pageX * -1 - 25; 
 
     var newvalueY = height * pageY * -1 - 50; 
 

 
     if ($('#bg').hasClass('transition')) { // if there is a transition 
 
     //wait for above timeout to remove transition 
 
     } else { // else no transition 
 

 
     $('#bg').css({ // move the background without transition 
 
      "background-position": newvalueX + "px  " + newvalueY + "px" 
 
     }); 
 
     } 
 
    } 
 
    }); 
 
});
#bg { 
 
    background: url('http://netsketched.com/pandf/img/sun-rise-clouds.jpg'); 
 
    background-size: 100% 100%; 
 
    width: 250px; 
 
    padding: 100px; 
 
} 
 
.transition { 
 
    /*class with transition*/ 
 
    transition: all .3s 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="bg"> 
 
    <h2>Hello, world!</h2> 
 
</div>

Documentation for setTimeout

+0

美麗。謝謝。 – John