繁体   English   中英

单击按钮时,如何为网站上的所有链接添加下划线?

[英]How do I add an underline for all the links on the website when I click the button?

经过一个小时的反复试验,创建了一个简单的脚本,我向您寻求帮助。 我想创建一个button ,单击它后会a网站上的所有选择器添加下划线样式。 我已经写了一个简单的function,可惜不行。 整页有大量的a选择器,我就不发整页的代码了。

JS文件:

function underlineLinks() {
  const links = document.querySelectorAll("a");
  links.style.textDecoration = "underline";
}

HTML 代码:

<button onclick="underlineLinks()">Underline</button>

函数中的 PHP 代码。php 文件:

function underline_links() {
  wp_enqueue_script( 'js-file', get_stylesheet_directory_uri() . '/js/underline.js');
}
add_action('wp_enqueue_scripts', 'underline_links');

对当前问题的原因并没有真正的解释,但是这里已经有足够多的了。

在整个文档或正文上使用 css 执行此操作似乎比单独遍历每个元素更简单。

 window.onload = function(){ document.getElementById('on').onclick = function(){ document.body.classList.add('underline'); }; document.getElementById('off').onclick = function(){ document.body.classList.remove('underline'); } }
 a{text-decoration: none} body.underline a{text-decoration: underline}
 <a>link 1</a> <a>link 2</a> <a>link 3</a> <button id = 'on'>on</button> <button id = 'off'>off</button>

一般来说,我会尽量避免使用 HTMLElements 的style属性,而是尝试使用类/属性。

根据要求编辑:

 a{text-decoration: none} body.underline a{text-decoration: underline}
 <a>link 1</a> <a>link 2</a> <a>link 3</a> <button onclick = "document.body.classList.toggle('underline')">toggle</button>

您正在尝试向从 .querySelectorAll() 返回的链接集合添加内联样式。 但是该集合没有style属性。 相反,在单击按钮时循环遍历集合中的所有链接并切换使用 CSS class。

 // When the button is clicked... document.querySelector("button").addEventListener("click", function(){ // Find all the <a> elements and loop over the collection of them document.querySelectorAll("a").forEach(function(link){ // Instead of working with inline styles (the style property), // just add or toggle the use of a pre-made CSS class. I'm using // toggle here, but if you just want the class added use.add("underline") // instead. link.classList.toggle("underline"); }); });
 a { text-decoration:none; }.underline { text-decoration:underline; }
 <a href="someURL">the text of the link</a> lorem ipsum <a href="someURL">the text of the link</a> lorem ipsum 2<a href="someURL">the text of the link</a> lorem ipsum <a href="someURL">the text of the link</a> lorem ipsum <a href="someURL">the text of the link</a> lorem ipsum <a href="someURL">the text of the link</a> lorem ipsum <a href="someURL">the text of the link</a> lorem ipsum <div> <button>Click to toggle underline</button> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM