单击复选框后,如何在文本中放置一行?



这是我到目前为止得到的,我很肯定问题出在这里.checkBox

var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
if (this.checkBox) {
inputItem.style.textDecoration = "line-through";
} else {inputItem.style.textDecoration = "none";}

你将不得不做这样的事情。当复选框更改时,通过查看checked属性来检查复选框是否已选中。如果为 true,请将标签的文本修饰设置为line-through否则可以将其设置为 none。

checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});

下面是一个完整的示例:

var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");

// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
console.log("Delete code!");
});

// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;

// Configure the check box
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';

checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});

// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);

// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);

list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input type="submit">
</form>
<ul id="list">
</ul>
</body>
</html>

你可以尝试这样的事情。只需创建一个 onclick 处理程序并检查元素的checked属性。相应地设置样式。

function toggleLineThrough(element) {
if (element.checked) {
document.getElementById("text").style.textDecoration = "line-through";
}
else {
document.getElementById("text").style.textDecoration = "none";
}

}
<input type="checkbox" onclick="toggleLineThrough(this)"/>
<p id="text">some random text</p>

相关内容

  • 没有找到相关文章