div hover上去变成input框 有保存和取消按钮
时间: 2024-03-16 12:43:37 浏览: 62
可以通过以下代码实现:
HTML部分:
```html
<div class="editable">这是可编辑的内容</div>
```
CSS部分:
```css
.editable {
display: inline-block;
border: 1px solid #ccc;
padding: 5px;
}
.editable input {
display: block;
border: none;
padding: 0;
margin: 0;
}
.editable input:focus {
outline: none;
}
.editable .save-btn,
.editable .cancel-btn {
display: none;
}
.editable:hover {
border-color: #333;
cursor: pointer;
}
.editable:hover input {
display: block;
width: 100%;
}
.editable:hover .save-btn,
.editable:hover .cancel-btn {
display: inline-block;
margin-left: 5px;
}
```
JS部分:
```javascript
const editable = document.querySelector('.editable');
const originalContent = editable.innerText;
editable.addEventListener('mouseenter', () => {
const input = document.createElement('input');
input.value = originalContent;
editable.innerText = '';
editable.appendChild(input);
const saveBtn = document.createElement('button');
saveBtn.innerText = '保存';
saveBtn.classList.add('save-btn');
editable.appendChild(saveBtn);
const cancelBtn = document.createElement('button');
cancelBtn.innerText = '取消';
cancelBtn.classList.add('cancel-btn');
editable.appendChild(cancelBtn);
});
editable.addEventListener('mouseleave', () => {
const input = editable.querySelector('input');
const saveBtn = editable.querySelector('.save-btn');
const cancelBtn = editable.querySelector('.cancel-btn');
if (input) {
editable.innerText = input.value;
}
if (saveBtn) {
saveBtn.remove();
}
if (cancelBtn) {
cancelBtn.remove();
}
});
```
这段代码实现了当鼠标移动到可编辑的div上时,将div的内容变成一个input框,并显示保存和取消按钮。当鼠标离开时,会根据用户的操作来决定是否保存修改的内容。
阅读全文