2016-01-18 51 views
-2

我还是很新的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){ 
} 
}); 

我欣赏所有帮助。非常感谢。

+0

你有一些HTML和JS,你已经与合作?如果你有一些请发布代码。谢谢! – ingernet

+0

[https://jsfiddle.net/s3u5bgr3/](https://jsfiddle.net/s3u5bgr3/)谢谢! – Eggsnuff

回答

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>