开发者问题收集

使用 javascript 更改文本颜色

2022-07-17
253

我这里有一个任务应用程序,允许用户创建任务并选择每个任务的类别。我希望当创建的任务是“个人”类别时,显示时文本的颜色属性为蓝色。否则,如果它是“工作”,那么它就是红色。以下是我在我的 javascript 文件中尝试过的。

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To-Do List</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <link rel="stylesheet" href="./style.css">
</head>
<body>

    <div class="container">
        <div class="row mb-5">
            <div class="col h1 text-white text-start text-center text-md-start text-lg-start">TO-DO APP</div>
        </div>

        <div class="row">
            <div class="h6 text-white text-start text-center text-md-start text-lg-start">CREATE A TO-DO</div>
        </div>

        <form id="todo-form">
            <div class="row mb-4">
                <div class="col">
                    <input class="form-control" name="newTask" type="text" placeholder="eg. Do the laundry"> 
                </div>     
            </div>
    
            <div class="row">
                <div class="h6 text-white text-start text-center text-md-start text-lg-start">CATEGORY</div>
            </div>
    
            <div class="row mb-3">
                <div class="col-6">
                    <input type="radio" class="btn-check" name="category" id="option1" value="Work">
                    <label class="col-12 btn btn-outline-danger p-4 text-white work-task" for="option1">Work</label>
                </div>
                <div class="col-6">
                    <input type="radio" class="btn-check" name="category" id="option2" value="Personal">
                    <label class="col-12 btn btn-outline-primary p-4 text-white personal-task" for="option2">Personal</label>
                </div>
            </div>
    
            <div class="row mb-4">
                <div class="col"><button type="submit" class="btn btn-secondary p-2 w-100 add-task" active>ADD TO-DO</button></div>
            </div>
        </form>

        <div class="row mb-2">
            <div class="h6 text-white text-start text-center text-md-start text-lg-start">TO-DO LIST</div>
        </div>

        <div class="todoList">

        </div>
    </div>
    <script src="main.js"></script>
</body>
</html>

Javascript:

const todoForm = document.getElementById("todo-form")

window.addEventListener("load", () => {
    todos = JSON.parse(localStorage.getItem("todos")) || []

    todoForm.addEventListener("submit", (e) => {
        e.preventDefault()
        if (e.target.elements.newTask.value != "") {
            const todo = {
                task: e.target.elements.newTask.value,
                category: e.target.elements.category.value
            }
    
            todos.push(todo);
    
            localStorage.setItem("todos", JSON.stringify(todos));
    
            e.target.reset()
    
            showList()
        }
    })
    
    showList();
})

function showList() {
    let outPut = '';
    let taskListShow = document.querySelector(".todoList")

    todos.forEach((data, index)=> {

        if (data.category == "Personal") {
            document.getElementById("todoContent").style.color = "blue"
        } else {
            document.getElementById("todoContent").style.color = "red"
        }

        outPut += `
        <div class="row todoList mb-3">
            <div class="col-10 col-lg-8 col-md-7 col-sm-6">
                <input id="todoContent" class="todoContent no-border text-white w-100" value="${data.task}" readonly>
            </div>
            <div class="col">
                <div class="row action">
                    <div class="col-6">
                        <button type="button" class="btn btn-secondary col-12" onClick="editItem(${index})">Edit</button>
                    </div>
                    <div class="col-6">
                        <button type="button" class="btn btn-danger col-12" onClick="deleteItem(${index})">Delete</button>
                    </div>       
                </div>
            </div>
        </div>`
    });
    taskListShow.innerHTML = outPut;
}

function deleteItem(index) {
    todos.splice(index, 1)
    localStorage.setItem("todos", JSON.stringify(todos))
    showList()
}

function editItem(index) {
    const taskAllName = document.querySelectorAll(".todoContent");
    const taskName = taskAllName[index];
    taskName.removeAttribute("readonly");
    taskName.focus();
    taskName.addEventListener("blur", (e) => {
        const newValue = e.target.value;
        const newTodos = todos.map((todo, i) =>
          i === index ? { ...todo, task: newValue } : { ...todo }
        );
        taskName.setAttribute("readonly", true);
        localStorage.setItem("todos", JSON.stringify(newTodos));
        todos = newTodos;
        showList();
    });
}

我目前收到错误:

"Uncaught TypeError: Cannot read properties of null (reading 'style')"

2个回答

因为你在元素创建之前就选中了它。这是我的想法:

const curColor = data.category == "Personal" ? "blue" : "red";
<input ...{other properties} style="color: ${curColor} !important" readonly>

但我不知道为什么样式的优先级比类低,也许你有什么逻辑,所以我在这里使用了 !important

isozl
2022-07-17

您正在尝试选择尚未加载的元素。请将 <script> 代码放在 body 末尾,或使用 <script src="script.js" defer> 属性进行修复。

AlignItems
2022-07-17