原生JS实现:获取点击元素类名并应用到另一元素
解决方法
你当前代码的第一个问题是document.querySelectorAll('li')返回的是NodeList集合,不能直接给整个集合绑定点击事件,得遍历每个列表项单独绑定。接下来按你的需求一步步实现:
关键步骤说明
- 遍历列表项绑定事件:用
forEach遍历每个<li>,给每个元素添加点击监听 - 获取点击元素的类名:在事件回调里通过
event.target拿到点击的<li>,再取它的className(因为你的每个li只有一个目标类,直接取就行) - 清空main的所有类:可以直接把
main的className设为空字符串,或者用classList.remove批量移除现有类 - 给main添加新类:用
classList.add把拿到的类名加给main
修改后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li class="typeface-alegreya"> Alegreya </li> <li class="typeface-alegreya-sans"> Alegreya Sans </li> <li class="typeface-archivo"> Archivo </li> <li class="typeface-archivo-narrow"> Archivo Narrow </li> </ul> <main class="typeface-chivo">The density of texture in a written or typeset page is called its color. This has nothing to do with red or green ink; it refers only to the darkness or blackness of the letterforms in mass. Once the demands of legibilty and logical order are satisfied, eveness of color is the typographer's normal aim. And color depends on four things: the design of the type, the spacing between the letters, the spacing between the words, and the spacing between the lines. None is independent of the others. </main> <script> const fontList = document.querySelectorAll('li'); const fontApply = document.querySelector('main'); // 遍历每个li绑定点击事件 fontList.forEach(item => { item.addEventListener("click", (e) => { // 获取点击li的类名 const clickedClass = e.target.className; // 移除main上的所有类 fontApply.className = ''; // 或者用classList的方式:fontApply.classList.remove(...fontApply.classList) // 给main添加新类 fontApply.classList.add(clickedClass); // 如果dialogFonts是已定义的弹窗,保留这句,否则可以删掉 // dialogFonts.close(); }); }); </script> </body> </html>
补充说明
如果你的<li>以后可能会有多个类(比如额外的样式类),可以给目标类统一加前缀(比如typeface-),然后通过classList过滤出带前缀的类:
// 过滤出以typeface-开头的类 const clickedClass = [...e.target.classList].find(cls => cls.startsWith('typeface-'));
这样即使li有其他类,也只会取到字体相关的类。
内容的提问来源于stack exchange,提问作者designtools
相关产品推荐
相关产品推荐

