可是现在点击空白区域不能创建<div>
时间: 2023-08-13 14:07:52 浏览: 132
vue 点击其他区域关闭自定义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) {
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 isClickedInsideFormula = false;
for (var i = 0; i < mathjaxFormulasContainer.children.length; i++) {
var formula = mathjaxFormulasContainer.children[i];
if (event.target === formula || formula.contains(event.target)) {
isClickedInsideFormula = true;
break;
}
}
if (isClickedInsideFormula) {
if (!selectedFormula) {
// 执行拖动事件
selectedFormula = event.target;
offsetX = event.clientX - selectedFormula.offsetLeft;
offsetY = event.clientY - selectedFormula.offsetTop;
}
} else {
// 执行添加 <div> 元素事件
if (!selectedFormula) {
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]);
}
}
});
}
}
});
</script>
</body>
</html>
```
现在,当你点击已有的 `<div>` 元素时,会触发拖动事件;当你点击空白区域时,会根据剪贴板中的 LaTeX 代码创建新的公式。非常抱歉之前给你带来的困惑,感谢你的耐心和理解!
阅读全文