我有this我一直在搞乱:
$('.container').mousedown(function(e) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
});
.container {
width: 300px;
height: 300px;
background-color: white;
border: 2px solid black;
margin: 0 auto;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
</div>
<div>Coords: <p class='coords'> </p> </div>
我正在尝试对它进行编程,这样当您在框内单击并移动鼠标时,坐标也会发生变化 - 如果您离开框,则不会更新。现在,坐标只会在您松开鼠标按钮然后再次单击时更改。帮助
答案 0 :(得分:2)
您需要创建更多mousedown函数。你也需要使用mousemove。以下是有关该文档的文档https://api.jquery.com/mousemove/
你可以这样做(fiddle)。
var mouse_clicked;
$('.container').mousedown(function(e) {
mouse_clicked = true;
});
$('.container').mouseup(function(e) {
mouse_clicked = false;
});
$('.container').mouseleave(function(e) {
mouse_clicked = false;
});
$('.container').mousemove(function(e) {
if (mouse_clicked) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
}
});
这是一种不同的方式,看起来更清洁
var mouse_clicked;
$('.container').on({
'mousedown': function() {
mouse_clicked = true;
},
'mouseup': function() {
mouse_clicked = false;
},
'mouseleave': function() {
mouse_clicked = false;
},
'mousemove': function(e) {
if (mouse_clicked) {
$('.coords').text(e.pageX + ' : ' + e.pageY);
}
}
});
答案 1 :(得分:0)
答案 2 :(得分:0)
我会像这样追踪它。
var mousePosition = { x: 0, y: 0};
var BUTTONS = { LEFT: 0, MIDDLE: 1, RIGHT: 2};
var mouseDown = [];
var mouseDownCount = 0;
var buttonInfo = document.getElementById("buttons");
var posInfo = document.getElementById("pos");
// Track mouse all the time.
document.addEventListener('mousemove', function storeMouse(event) {
mousePosition = {
x: event.clientX,
y: event.clientY
};
});
document.addEventListener('mousedown', function (event) {
mouseDown[event.button] = true;
++mouseDownCount;
});
document.addEventListener('mouseup', function (event) {
mouseDown[event.button] = false;
--mouseDownCount;
});
function checkMouseStuff() {
var buttons = [];
if (mouseDownCount) {
for (var i = 0; i < mouseDown.length; ++i) {
if (mouseDown[i]) {
buttons.push("Button: " + i);
}
}
}
buttonInfo.textContent = buttons.join(", ");
posInfo.textContent = mousePosition.x + " : " + mousePosition.y;
}
window.setInterval(checkMouseStuff, 10);
<p id="pos"></p>
<p id="buttons"></p>