将添加的代码写进html,还有鼠标放开不清除选中<div>
时间: 2023-12-08 22:03:57 浏览: 186
鼠标移动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 selectedDiv = null;
var offsetX = 0;
var offsetY = 0;
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) {
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]);
}
}
});
});
document.addEventListener("mousedown", function(event) {
if (event.target.classList.contains("mathjax-formula")) {
selectedDiv = event.target;
offsetX = event.clientX - parseInt(selectedDiv.style.left);
offsetY = event.clientY - parseInt(selectedDiv.style.top);
}
});
document.addEventListener("mousemove", function(event) {
if (selectedDiv) {
selectedDiv.style.left = event.clientX - offsetX + "px";
selectedDiv.style.top = event.clientY - offsetY + "px";
}
});
document.addEventListener("mouseup", function() {
// Do nothing. Keep the selected div as it is.
});
</script>
</body>
</html>
```
这段代码在已有的基础上添加了以下功能:
- 鼠标按下事件(mousedown):当用户按下鼠标时,如果点击的是<div>元素,则记录选中的<div>元素,并计算鼠标位置与<div>元素左上角的偏移量。
- 鼠标移动事件(mousemove):当用户按下鼠标并移动时,如果有选中的<div>元素,则根据鼠标位置和偏移量来更新<div>元素的位置。
- 鼠标放开事件(mouseup):当用户释放鼠标时,不执行任何操作,保持选中的<div>元素不变。
这样修改后,选中的<div>元素将保持其位置,直到再次点击其他位置或拖动该元素。
阅读全文