需要更改每次移动鼠标时的背景位置
问题描述:
我需要更改每次移动鼠标时的背景位置。图像设置为背景,这里是图像,需要更改每次移动鼠标时的背景位置
https://pbdlbd.org/ipositive/wp-content/uploads/2015/02/one10.jpg
,我想移动每个鼠标移动的背景位置。这个图像有4个部分(每个部分的高度为523px),首先它会显示顶部,鼠标移过后会显示第二部分,在另一个鼠标移动时它会显示第三部分,并在第四部分后重复进一步的鼠标移动它。从图像中移除鼠标后,它将显示图像的默认顶部。
这样的事情,
document.getElementById("#ipos .flex_cell").onmousemove = function() {
//Set background position 523px bottom on each mouse move
#ipos .flex_cell.style.background-position = center -523px (here i can't make it so that it changes to -1046px by code);
}
这里是网站,http://pbdlbd.org/ipositive/
预先感谢您
答
对于跳跃从第一到第四部分,你只需要读取(或从读分开变量)当前位置并添加偏移量并将此总和设置为目标。
您还必须在函数中使用if条件来检测从第4部分跳回到第1部分。
所以可以将(未经测试):
var offset = 0;
var jump = 523;
$('#ipos .flex_cell').mousemove(function() {
if (offset > (3 * jump)) {
offset = 0;
}
else {
offset += jump;
}
$('#ipos .flex_cell').css('background-position', 'center ' + (offset * -1) + 'px');
});
但是:这仅是回答你的问题,但它并没有解决问题。因为mousemove是EVERY PIXEL,所以你移动元素..所以这个代码会促使massiv闪烁。所以你还应该记住上一次的光标位置,并且只作用于一个确定的移动距离。
BR添
答
您可以使用jQuery的.mousemove
得到的鼠标移动每一个实例。这将注册每个像素。所以我将它弹出一个循环,并将每次移动鼠标的计数除以40(随意相应地更改)。每当鼠标移动40个像素时,我会向图像添加一个类,以便为每个阶段移动它,并在其循环后重置。看到下面的代码和here是一个小提琴。希望它是有道理的,祝你好运!
$('.wrapper').on('mouseover' , function(){
var count = 0;
\t $('.wrapper').on('mousemove' , function(){
\t var move = count/40;
if (move==1){
$('.image').addClass('second');
}
if (move==2){
$('.image').addClass('third');
}
if (move==3){
$('.image').addClass('fourth');
}
\t count++;
if(move>=4){
\t \t count=0;
$('.image').removeClass('fourth third second');
return count;
}
});
});
$('.wrapper').on('mouseout' , function(){
\t $('.image').removeClass('fourth third second');
});
.wrapper {
width: 200px;
height: 217px;
overflow:hidden;
}
.image{
width:100%;
}
.second{
margin-top:-217px;
}
.third{
margin-top:-435px;
}
.fourth{
margin-top:-652px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<img class="image" src="http://pbdlbd.org/ipositive/wp-content/uploads/2015/02/one10.jpg" alt=""/>
</div>