我正在构建一个简单的jQuery函数来使用mousemove移动元素。我正在尝试使用.css('转换','翻译......'),但不知怎的,我无法让它发挥作用。
$(document).on('mousemove', function (ev) {
var mouseX = ev.originalEvent.pageX;
var mouseY = ev.originalEvent.pageY;
$('.followmouse').each(function () {
var objectX = $(this).offset().left;
var objectY = $(this).offset().top;
var diffX = mouseX - objectX;
var diffY = mouseY - objectY;
$(this).css('transform', 'translate(' + diffX + ', ' + diffY + ')');
});
});

html, body {
height: 100%;
display: flex;
justify-content: center;
}
.followmouse {
width: 100px;
height: 100px;
background: black;
align-self: center;
margin: 16px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="followmouse"></div>
<div class="followmouse"></div>
</body>
&#13;
我试图应用类似问题的答案,但似乎没有一个对我有用。有什么想法吗?
答案 0 :(得分:0)
解决!
我忘了在变量...
之后插入单位(px)答案 1 :(得分:0)
不知道您想要在这里实现什么,但您只需将px
附加到您的翻译价值'translate(' + diffX + 'px, ' + diffY + 'px)'
见下面的代码:
$(document).on('mousemove', function (ev) {
console.log(ev.target,this);
var mouseX = ev.originalEvent.pageX;
var mouseY = ev.originalEvent.pageY;
$('.followmouse').each(function () {
var objectX = $(this).offset().left;
var objectY = $(this).offset().top;
var diffX = mouseX - objectX;
var diffY = mouseY - objectY;
console.log(diffX,diffY);
$(this).css('transform', 'translate(' + diffX + 'px, ' + diffY + 'px)');
});
});
html, body {
height: 100%;
display: flex;
justify-content: center;
}
.followmouse {
width: 100px;
height: 100px;
background: black;
align-self: center;
margin: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="followmouse"></div>
<div class="followmouse"></div>
</body>