背景不会发生变化

时间:2015-09-12 21:46:18

标签: javascript html css html5 css3

我的代码似乎没有被解雇,由于一些奇怪的原因,我不知道为什么。鼠标移动应该会导致背景移动,但没有任何反应。

<html>

<div id="pageBg">
</div>

</html>

<style>
#pageBg {
background: url(http://****.com/tes.jpg) no-repeat 0 0      
scroll;    
height: auto;
left: 0;
min-height: 1920px;
min-width: 1080px;
overflow: hidden;
position: fixed;   
top: 0;
width: 100%;
}

</style>

<script>

$(document).ready(function(){
$('#pageBg').mousemove(function(e){
  var mousePosX = (e.pageX/$(window).width())*100;
  $('#pageBg').css('background-position-x', mousePosX +'%');

   var mousePosY = (e.pageY/$(window).height())*100;
$('#pageBg').css('background-position-y', mousePosY +'%');
}); 
});

</script>

1 个答案:

答案 0 :(得分:2)

当你以正确的顺序编写代码并包含jQuery时,一切似乎都很好:

$(document).ready(function() {
  $('#pageBg').mousemove(function(e) {
    var mousePosX = (e.pageX / $(window).width()) * 100;
    $('#pageBg').css('background-position-x', mousePosX + '%');

    var mousePosY = (e.pageY / $(window).height()) * 100;
    $('#pageBg').css('background-position-y', mousePosY + '%');
  });
});
#pageBg {
  background: url(http://www.europeantouchskincare.com/tes.jpg) no-repeat 0 0 scroll;
  height: auto;
  left: 0;
  min-height: 1920px;
  min-width: 1080px;
  overflow: hidden;
  position: fixed;
  top: 0;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pageBg">
</div>

所以你的最终代码将是:

<html>
    <head>
        <style>
        #pageBg {
            background: url(http://www.europeantouchskincare.com/tes.jpg) no-repeat 0 0      
            scroll;    
            height: auto;
            left: 0;
            min-height: 1920px;
            min-width: 1080px;
            overflow: hidden;
            position: fixed;   
            top: 0;
            width: 100%;
        }
        </style>
    </head>
    <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#pageBg').mousemove(function(e){
                    var mousePosX = (e.pageX/$(window).width())*100;
                    $('#pageBg').css('background-position-x', mousePosX +'%');
                    var mousePosY = (e.pageY/$(window).height())*100;
                    $('#pageBg').css('background-position-y', mousePosY +'%');
                }); 
            });
        </script>
        <div id="pageBg">
        </div>
    </body>
</html>