jquery效果div位置随鼠标移动而变化的代码怎么写

当前的html

<div id="sc"> 联系我们 </div>
当前的css样式

<style>
body{ overflow:hidden;}
#sc{ width:180px; height:200px; border:1px solid #ddd; position:absolute; right:-150px; top:30%;}
</style>
当前的js代码

$(document).ready(function(){
$('#sc').mouseover(function(){
$('#sc').animate({right:'0px',opacity:'1'},500);
})
$('#sc').mouseout(function(){
$('#sc').animate({right:'-150px',opacity:'0.5'},500);
})
})

我现在实现的效果就是普通的侧边联系客服的效果,鼠标放上去,它会从右边的地方出来,
然后我想加个效果,当我鼠标滚动的时候,它右边距离top的位置也跟着下来,
求高手帮忙写一下 实在不会了 谢谢

完全不需要js实现,除非你要兼容IE6


只要把sc的样式

position:absolute;

 改为

position:fixed;

 即可 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-27

全兼容代码参考如下:

<style>
/* required to avoid jumping */
#commentWrapper { 
  left: 450px;
  position: absolute;
  margin-left: 35px;
  width: 280px;
}

#comment {
  position: absolute;
  top: 0;
  /* just used to show how to include the margin in the effect */
  margin-top: 20px;
  border-top: 1px solid purple;
  padding-top: 19px;
}

#comment.fixed {
  position: fixed;
  top: 0;
}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

<script>
$(document).ready(function () {  
  var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();
  
    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#comment').addClass('fixed');
    } else {
      // otherwise remove it
      $('#comment').removeClass('fixed');
    }
  });
});
</script>

本回答被提问者采纳
第2个回答  2015-10-09
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://www.hsspw.com/hssc/JS/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">

$(document).ready(function(){
$('#mo').mousemove(function(e){
n=$('#xxx').val()-50;

m=$('#yyy').val()-50;

$('#mo').css({top:m+'px', left:n+'px'});
});
});
function mouseMove(ev)
{
Ev= ev || window.event;
var mousePos = mouseCoords(ev);
document.getElementById("xxx").value = mousePos.x;
document.getElementById("yyy").value = mousePos.y;
}
function mouseCoords(ev)
{
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return{
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
document.onmousemove = mouseMove;
</script>

鼠标X轴:
<input id='xxx' type='text'>
鼠标Y轴:
<input id=yyy type=text>

<div id='mo' style='position:absolute;width:200px;height:200px;background:red'>111</div>
</body>
</html>
相似回答