2016-10-25 117 views
0

我試圖讓這個背景圖像在mousemove上移動。現在圖像不會移動,只是保持不變。另外,我認爲腳本存在錯誤,但我無法弄清楚哪個部分是錯誤的。在mousemove上移動背景圖像

/* background movement by mouse*/ 
 

 
$(document).ready(function() { 
 
    var movementStrength = 25; 
 
    var height = movementStrength/$(window).height(); 
 
    var width = movementStrength/$(window).width(); 
 
    $("#top-image").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; 
 
    $('#top-image').css("background-position", newvalueX + "px  " + newvalueY + "px"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg"> 
 
</div>

+0

你有你的HTML添加圖片標籤,你試着用背景位置,這不是任何意義動畫。你能確定一下你真正想做什麼以及你現在嘗試做什麼嗎? – mlbd

回答

1

既然你沒有使用背景圖片,我不認爲你影響了什麼嘗試修改背景位置屬性。此外,我會根據圖像尺寸而不是窗口尺寸來確定移動量。試試這個:

$(document).ready(function() { 
 
       var movementStrength = 25; 
 
       var img = document.getElementById('top-image'); 
 
       var imagewidth = img.clientWidth; 
 
       var imageheight = img.clientHeight; 
 
       var height = movementStrength/imageheight; 
 
       var width = movementStrength/imagewidth; 
 
       $("#top-image").mousemove(function(e) { 
 
        var pageX = e.pageX - ($(window).width()/2); 
 
        var pageY = e.pageY - ($(window).height()/2); 
 
        var newvalueX = width * pageX * -1; 
 
        var newvalueY = height * pageY * -1; 
 
        $(this).css("margin-left", newvalueX + "px"); 
 
        $(this).css("margin-top", newvalueY + "px"); 
 
       }); 
 
       });
#top-image { 
 
    width: 500px; 
 
    height: auto; 
 
    padding-top:20px; 
 
} 
 

 
.container { 
 
    width: 600px; 
 
    height: 380px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
TITLE 
 
</div> 
 
<div class="container"> 
 
    <img id="top-image" src="https://static.pexels.com/photos/4164/landscape-mountains-nature-mountain.jpeg"> 
 
</div> 
 
<div> 
 
Some More Text 
 
</div>

+0

除非頁面的其他部分完全定位,否則我認爲這不會起作用。整個身體會被移動。 – Lemmmy

+1

如果你製作的容器比img大,你會沒事的。 https://jsfiddle.net/9gme82zb/11/ – UltrasoundJelly