css Cant classList.将类切换到svg元素

kkbh8khc  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(118)

我想切换一个类到一个svg内的按钮标签点击这个确切的按钮。
下面是我的按钮的HTML代码:

<button class="control-btn" id="control-btn-edit">
                    <svg id="edit-svg" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 528.899 528.899" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <path d="M328.883,89.125l107.59,107.589l-272.34,272.34L56.604,361.465L328.883,89.125z M518.113,63.177l-47.981-47.981 c-18.543-18.543-48.653-18.543-67.259,0l-45.961,45.961l107.59,107.59l53.611-53.611 C532.495,100.753,532.495,77.559,518.113,63.177z M0.3,512.69c-1.958,8.812,5.998,16.708,14.811,14.565l119.891-29.069 L27.473,390.597L0.3,512.69z"></path> </g> </g></svg>
                </button>

下面是我想添加到svg中的类的css代码:

.pressed {
  fill: #19ba00;
}

最后,这里是我想添加的函数的JavaScript代码(该函数包含引用不同元素的代码):

const tableCell = document.querySelector(".divTableCell");
const cellInput = document.querySelector(".cellInput");
const table = document.querySelector(".divTable");
const display = document.querySelector(".display");
const navButton = document.querySelector(".nav-button");
const addButton = document.querySelector("#control-btn-add");
const genButton = document.querySelector("#control-btn-generate");
const editButton = document.querySelector("#control-btn-edit");
const editButtonSvg = document.querySelector("#edit-svg");

editButton.addEventListener("click", () => {
    let allCellInputs = document.querySelectorAll(".cellInput");
    for (let i = 0; i < allCellInputs.length; i++) {
        allCellInputs[i].toggleAttribute("disabled");
    }
    editButtonSvg.classList.toggle("pressed");
});

正如您所看到的,我已经尝试使用classList.toggle()方法,但它不起作用。当我手动将类添加到html svg元素时,它也不工作。
我尝试将类改为id并使用toggleAttribute()方法,但效果不佳。
我发现当我使用setAttribute()方法时,它工作得很好,但是我没有得到我想要的切换效果。

qvtsj1bj

qvtsj1bj1#

实际上我检查了你的代码,它的工作唯一的区别是,我增加了宽度的图标

#edit-svg {
        width: 24px;
    }

相关问题