图像更改鼠标移动

时间:2016-01-18 04:16:26

标签: javascript jquery html css

我还是jquery和javascript的新手。

每当鼠标向左移动时,我都会尝试更改图像。例如,每移动50px鼠标左移,图像就会改变。

我不知道从哪里开始。但是我在JSFiddle找到了这个。 不太确定如何从那里前进。

$( "div" ).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
var clientCoords = "( " + event.clientX + ", " + event.clientY + " )";
$( "span:first" ).text( "( event.pageX, event.pageY ) : " + pageCoords );
$( "span:last" ).text( "( event.clientX, event.clientY ) : " + clientCoords );
if(event.pageX){
}
});

我感谢所有的帮助。非常感谢你。

1 个答案:

答案 0 :(得分:0)

找到了一个有趣的jsfiddle来检测鼠标移动,取自this question

我能够使用四张图片。只需创建更多类,oldMath变量和else if语句以获取更多信息。



var oldMath = 0;
var oldMath2 = 50;
var oldMath3 = 100;
$('#image').mousemove(function(event) {
    var startingTop = 10,
        startingLeft = 22,
        math = Math.round(Math.sqrt(Math.pow(startingTop - event.clientY, 2) +Math.pow(startingLeft - event.clientX, 2))) + 'px';
    $('#currentPos').text('you are at :' + math); // remove this line if you don't want the span
    
    if(Math.abs(parseInt(math) - oldMath) > 50){
        //you have moved 5 pixles, put your stuff in here
        $('.example').removeClass('example').addClass('example2').text('it\'s fall!');
        
        
        oldMath = parseInt(math);
  } else if(Math.abs(parseInt(math) - oldMath2) > 50){
        //you have moved 5 pixles, put your stuff in here
        $('.example2').removeClass('example2').addClass('example3').text('it\'s winter!');
        
        
        oldMath2 = parseInt(math);
  } else if(Math.abs(parseInt(math) - oldMath3) > 50){
        //you have moved 5 pixles, put your stuff in here
        $('.example3').removeClass('example3').addClass('example4').text('it\'s spring!');
        
        
        oldMath3 = parseInt(math);
    }
});

#image {
  width: 500px;
  height: 500px;
  color: white;
  font-size: 25px;
    }
.example {
  background: url('http://writers.uclaextension.edu/wp-content/uploads/2013/03/summer.jpg');
}
.example2 {
  background: url('http://pcafalcons.com/wp-content/uploads/2014/10/Fall_image.jpg');
}
.example3 {
  background: url('http://cdn1.theodysseyonline.com/files/2015/12/04/635848557150633136-120303261_winter.jpg');
}
.example4 {
  background: url('http://sites.psu.edu/showerthoughts/wp-content/uploads/sites/21601/2015/03/spring-flowers-background-3.jpg');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="currentPos"></span>
<div class="example" id="image">hover to change the season</div>
&#13;
&#13;
&#13;