每个 mouse.x 的设置 CSS 值
Settings CSSvalues per mouse.x
就这么简单。我覆盖了默认的 mousemove 事件,并将其替换为:
function onDocumentMouseMove(e) {
e.preventDefault();
e.stopPropagation();
mouse.x = (e.clientX / WIDTH) * 2 - 1;
mouse.y = -(e.clientY / HEIGHT) * 2 + 1;
var x = mouse.x + "px";
$('#gun').css('left', x);
}
然而,这不起作用,枪只是按照原来的位置渲染的。请帮忙,因为我需要了解这样的基本知识才能成为一名程序员。我只是太笨了。也许我需要 Whosebug 作为补偿?
感谢所有努力回答问题的人!
- 诺亚
您似乎在使用 jQuery,因此您需要类似的东西;
$(document).ready(function() {
var $gun = $('#gun');
var mouseMove = function (e) {
$gun.css('left', e.clientX);
$gun.css('top', e.clientY);
}
window.addEventListener('mousemove', mouseMove, false);
}
您需要确保为枪支元素提供正确的 CSS,以便位置正确。
我认为如果您声明 WIDTH
、HEIGHT
、mouse
正确,您的代码通常会起作用。我给你做了一个demo,你可以看到结果。
$(document).ready(function () {
/*
* place jquery objects & constants declarations outside of
* event handler so you don't redeclare them every time the
* event fires.
*/
var $gun = $('#gun');
var WIDTH = $gun.css('width').match(/\d*/)[0];
var HEIGHT = $gun.css('height').match(/\d*/)[0];
$('.playground').on('mousemove', function (e) {
e.preventDefault();
e.stopPropagation();
var mouse = {};
// your definition of mousemove behavior
mouse.x = (e.clientX / WIDTH) * 2 - 1;
mouse.y = -(e.clientY / HEIGHT) * 2 + 1;
// your DOM manipulations
$gun.css('left', mouse.x);
});
});
就这么简单。我覆盖了默认的 mousemove 事件,并将其替换为:
function onDocumentMouseMove(e) {
e.preventDefault();
e.stopPropagation();
mouse.x = (e.clientX / WIDTH) * 2 - 1;
mouse.y = -(e.clientY / HEIGHT) * 2 + 1;
var x = mouse.x + "px";
$('#gun').css('left', x);
}
然而,这不起作用,枪只是按照原来的位置渲染的。请帮忙,因为我需要了解这样的基本知识才能成为一名程序员。我只是太笨了。也许我需要 Whosebug 作为补偿?
感谢所有努力回答问题的人!
- 诺亚
您似乎在使用 jQuery,因此您需要类似的东西;
$(document).ready(function() {
var $gun = $('#gun');
var mouseMove = function (e) {
$gun.css('left', e.clientX);
$gun.css('top', e.clientY);
}
window.addEventListener('mousemove', mouseMove, false);
}
您需要确保为枪支元素提供正确的 CSS,以便位置正确。
我认为如果您声明 WIDTH
、HEIGHT
、mouse
正确,您的代码通常会起作用。我给你做了一个demo,你可以看到结果。
$(document).ready(function () {
/*
* place jquery objects & constants declarations outside of
* event handler so you don't redeclare them every time the
* event fires.
*/
var $gun = $('#gun');
var WIDTH = $gun.css('width').match(/\d*/)[0];
var HEIGHT = $gun.css('height').match(/\d*/)[0];
$('.playground').on('mousemove', function (e) {
e.preventDefault();
e.stopPropagation();
var mouse = {};
// your definition of mousemove behavior
mouse.x = (e.clientX / WIDTH) * 2 - 1;
mouse.y = -(e.clientY / HEIGHT) * 2 + 1;
// your DOM manipulations
$gun.css('left', mouse.x);
});
});