需要同时按住鼠标并移动鼠标才能拖动<div>
时间: 2023-08-13 14:06:08 浏览: 178
如果你希望只有同时按住鼠标左键并移动鼠标时才能拖动 `<div>` 元素,你可以在 `mousemove` 事件中添加一个判断条件来检查鼠标左键是否被按下。下面是更新后的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>MathJax Example</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
<style>
.mathjax-formula {
font-size: 2.8em;
background-color: green;
position: absolute;
left: 0;
top: 0;
cursor: move;
padding: 5px;
border-radius: 5px;
color: white;
}
</style>
</head>
<body>
<div id="mathjax-formulas-container"></div>
<script>
var formulas = [];
var selectedFormula = null;
var offsetX = 0;
var offsetY = 0;
document.addEventListener("mousedown", function(event) {
if (event.button === 0) {
var target = event.target;
if (target.classList.contains("mathjax-formula")) {
selectedFormula = target;
offsetX = event.clientX - selectedFormula.offsetLeft;
offsetY = event.clientY - selectedFormula.offsetTop;
document.addEventListener("mousemove", moveFormula);
}
}
});
function moveFormula(event) {
if (selectedFormula && event.buttons === 1) {
selectedFormula.style.left = event.clientX - offsetX + "px";
selectedFormula.style.top = event.clientY - offsetY + "px";
} else {
document.removeEventListener("mousemove", moveFormula);
}
}
document.addEventListener("mouseup", function(event) {
if (event.button === 0) {
selectedFormula = null;
document.removeEventListener("mousemove", moveFormula);
}
});
document.addEventListener("click", function(event) {
var mathjaxFormulasContainer = document.getElementById("mathjax-formulas-container");
navigator.clipboard.readText().then(function(text) {
if (text) {
var latexCode = text.trim();
if (latexCode && !selectedFormula) {
var newFormula = document.createElement("div");
newFormula.className = "mathjax-formula";
newFormula.style.left = event.clientX + "px";
newFormula.style.top = event.clientY + "px";
newFormula.innerText = latexCode;
mathjaxFormulasContainer.appendChild(newFormula);
formulas.push({
latexCode: latexCode,
position: {
x: event.clientX,
y: event.clientY
}
});
MathJax.Hub.Queue(["Typeset", MathJax.Hub, newFormula]);
}
}
});
});
</script>
</body>
</html>
```
现在,只有同时按住鼠标左键并移动鼠标时,选中的 `<div>` 元素才会跟随鼠标移动。在 `mousemove` 事件中,我添加了一个条件 `event.buttons === 1` 来检查鼠标左键是否被按下,以及在 `mouseup` 事件中添加了条件 `event.button === 0` 来检查是否释放鼠标左键。这样,只有在按住鼠标左键并移动鼠标时,选中的元素才会移动,而不是在单击时移动。
请注意,这里我假设你只关注鼠标左键的操作,当按下其他鼠标按键时不会触发拖动操作。如果你需要同时支持其他鼠标按键,请相应地调整条件判断。
阅读全文