拖动<div>解决了,可视放开鼠标后创建出了多余的<div>
时间: 2023-11-11 16:04:23 浏览: 135
可视区拖动div效果
非常抱歉,我之前的修正还是有问题。下面是修正后的代码,可以解决放开鼠标后创建多余 `<div>` 的问题:
```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) {
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", function(event) {
if (selectedFormula) {
var xDiff = event.clientX - selectedFormula.offsetLeft - offsetX;
var yDiff = event.clientY - selectedFormula.offsetTop - offsetY;
if (xDiff >= 0 && xDiff <= selectedFormula.offsetWidth && yDiff >= 0 && yDiff <= selectedFormula.offsetHeight) {
selectedFormula.style.left = event.clientX - offsetX + "px";
selectedFormula.style.top = event.clientY - offsetY + "px";
}
}
});
document.addEventListener("mouseup", function(event) {
selectedFormula = null;
});
document.addEventListener("click", function(event) {
var mathjaxFormulasContainer = document.getElementById("mathjax-formulas-container");
var target = event.target;
if (target === mathjaxFormulasContainer) {
navigator.clipboard.readText().then(function(text) {
if (text) {
var latexCode = text.trim();
if (latexCode) {
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]);
}
}
});
} else if (target.classList.contains("mathjax-formula")) {
selectedFormula = target;
offsetX = event.clientX - selectedFormula.offsetLeft;
offsetY = event.clientY - selectedFormula.offsetTop;
}
});
</script>
</body>
</html>
```
现在,当你点击空白区域时才会创建新的 `<div>` 元素,同时拖动已存在的 `<div>` 元素也不会创建多余的元素。非常抱歉之前给你带来的困扰,感谢你的耐心和理解!
阅读全文